春天mvc 3没有下载文本文件

时间:2018-02-16 06:42:08

标签: java spring file spring-mvc

  

我可以创建该文件但无法下载。我试图通过ajax调用下载该文件。我能够收到文件名和文件内容,并成功地将内容写入应用程序目录中的文件,但我无法下载该文件。我的代码如下: -

Ajax代码 - :

downloadButton.onclick = function() {
        //alert(payLoadID); 
             $.ajax({
                 type: "POST",
                 url: "payloadAjax",
                 data: { payloadData: document.getElementById("modal_paragraph").innerHTML, id: payLoadID },
                 success : function(data) {
                    alert("SUCCESS: " +data);
                //  modal.style.display = "none";
                //  $("body").css("overflow","auto");
                },
                error : function(e) {
                    alert("ERROR: "+ e);
                },
                done : function(e) {
                    alert("DONE");
                }
            }) 

    }
  

这是java代码 - :

@RequestMapping(value = "/payloadAjax", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)//, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody
void download(@RequestParam("payloadData") String payloadData, @RequestParam("id") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println("id : " +fileName);
    System.out.println("payloadData : " +payloadData);

    /* File creation code is here. */
    String FOLDER = "/downloadDir";
    String FILE_NAME = fileName +".txt";

    String appPath = request.getRealPath("");
    System.out.println("appPath = " + appPath);

    File downloadDirectory = new File(appPath + FOLDER);
    if(!downloadDirectory.exists() || !downloadDirectory.isDirectory()) {
        downloadDirectory.mkdir();
        System.out.println("Directory Created");
    } else {
        System.out.println("Directory already exists.");
    }

    File uploadFile = new File(downloadDirectory, FILE_NAME);

    if(uploadFile.exists()) {
        uploadFile.delete();
        System.out.println(uploadFile.getName() +" Has been deleted.");
    }

    try {
        uploadFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("New File successfully created.");

    try
    {
        PrintWriter writer = new PrintWriter(uploadFile, "UTF-8");
        writer.println(payloadData);
        writer.flush();
        writer.close();

        System.out.println("File successfully written.");
    }
    catch(Exception ex) {
        ex.printStackTrace();
    }

    if (uploadFile.exists()) {
        System.out.println("Upload file exists. Ready to download....");
    } else {
        System.out.println("Sorry File not found!!!!");
    }

    /*File creation code successfully completed.*/

    /*File download code starts here */

    /*HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_HTML);
    headers.setContentLength(uploadFile.length());
    headers.setContentDispositionFormData("attachment", "Soubhab_Pathak.txt");
    InputStreamResource isr = new InputStreamResource(new FileInputStream(uploadFile));
    return new ResponseEntity<InputStreamResource>(isr, headers, HttpStatus.OK);*/

    if(response == null) {
        System.out.println("Response is null.");
    } else {
        System.out.println("Response is not null.");
    }

    System.out.println("111");
    OutputStream out = response.getOutputStream();
    System.out.println("112");
    FileInputStream in = new FileInputStream(uploadFile);
    System.out.println("113");
    response.setContentType(MediaType.TEXT_PLAIN_VALUE);
    response.setHeader("Content-Disposition", "attachment; filename=" + FILE_NAME);
    response.setHeader("Content-Length", uploadFile.length() +"");
    FileCopyUtils.copy(in, out);
    System.out.println("114");
    response.flushBuffer();
    System.out.println("115"); 
     /*File download code completes here.*/
}
  

日志如下   enter image description here

     

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

最后我能够解决问题。这也是如何使用ajax在Spring MVC中下载字符串作为文件的示例。解决方案如下 - :

1)一个控制器动作,用于从ajax调用接收字符串,并将该字符串存储在应用程序服务器的文件中。

2)另一个控制器操作,您需要编写文件下载代码,此操作将收到GET请求。

3)在成功部分的ajax调用中只需调用第二个动作方法来下载文件。

现在代码工作正常。