繁体   English   中英

春天没有下载文件

[英]Files not getting Downloaded in Spring

有一个页面,我有文件列表。 在浏览任何.txt文件时,必须先下载该文件,并显示一条通知,作为我们在GoogleChrome上下载任何内容时收到的通知。

这是我的Js,它在单击.txt文件后被调用。在这里,我正在执行的操作是获取所选文件的文件名和文件路径。 然后使用ajax将那些文件名和文件路径发送到spring servlet。

if (options.downloadable) {
  $(easyTree).find('.easy-tree-toolbar').append('<div class="fileDownload"><button class="btn btn-default btn-sm btn-primary"><span class="glyphicon glyphicon-circle-arrow-down"></span></button></div>');
  $(easyTree).find('.easy-tree-toolbar .fileDownload > button').attr('title', options.i18n.downloadTip).click(function() {
    var selected = getSelectedItems();
    var fileName = $(selected).find(' > span > a').text();
    alert("fileName**" + fileName);
    var hrefValue = $(selected).find(' > span > a').attr('href');
    alert("hrefValue**" + hrefValue);
    if (selected.length <= 0) {
      $(easyTree).prepend(warningAlert);
      $(easyTree).find('.alert .alert-content').html(options.i18n.downloadNull);
    } else {
      $.ajax({
        url: "/ComplianceApplication/downloadFileFromDirectory",
        type: "GET",
        data: {
          hrefValue: hrefValue,
          fileName: fileName
        },
        success: function(data) {

          //$(selected).remove();
          //window.location.reload();
        },
        error: function(e) {

        }
      });

    }
  });
}

这是我的springController。 在这里,我可以正确获取所有数据,但问题是文件没有下载,甚至没有出现任何错误,因此我可以知道自己在做什么错误。

@RequestMapping(value="/downloadFileFromDirectory",method = RequestMethod.GET)
    public  @ResponseBody void downloadFileFromDirectory(@PathVariable("fileName") String fileName,@RequestParam(value = "hrefValue") String hrefValue,HttpServletRequest request, HttpServletResponse response,Model model){
        System.out.println("hrefValue***"+hrefValue);

       String filePath = hrefValue;
        ServletContext context = request.getSession().getServletContext();
        File downloadFile = new File(filePath);
        FileInputStream inputStream = null;
        OutputStream outStream = null;
        try {
            inputStream = new FileInputStream(downloadFile);
            response.setContentLength((int) downloadFile.length());
            response.setContentType(context.getMimeType(downloadFile.getName()));
            // response header
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
            //String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
            response.setHeader(headerKey, headerValue);
            // Write response
            outStream = response.getOutputStream();
            IOUtils.copy(inputStream, outStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inputStream)
                    inputStream.close();
                if (null != outStream)
                    outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 }

有什么建议么 ???

我通常使用这种代码没有问题:

public ResponseEntity<InputStreamResource> downloadFile(@PathVariable("idForm") String idForm)
{
    try
    {

            File parent = new File(csvFilesPath);
            File file = new File(parent, idForm+".csv");
            HttpHeaders respHeaders = new HttpHeaders();
            MediaType mediaType = new MediaType("text","csv");
            respHeaders.setContentType(mediaType);
            respHeaders.setContentLength(file.length());
            respHeaders.setContentDispositionFormData("attachment", "file.csv");
            InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
            return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
        }
    catch (Exception e)
    {
        String message = "Errore nel download del file "+idForm+".csv; "+e.getMessage();
        logger.error(message, e);
        return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

问题出在您的ajax代码中,因此您可以使用JQuery File Download。

就这么简单

$.fileDownload('/url/to/download.pdf');

在这里您可以看到一个教程

http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM