如何使用AJAX调用在Spring下载Word文件?

时间:2017-05-22 12:45:59

标签: jquery ajax spring spring-mvc doc

我想下载一个.doc文件,但我收到了一些警告:

  

#[http-nio-8080-exec-9]警告       org.springframework.web.servlet.handler.SimpleMappingExceptionResolver       处理程序执行导致异常:无法实例化e标准       序列化程序(类型为com.fasterxml.jackson.databind.ser.std.NullSerializer):       类com.fasterxml.jackson.databind.ser.BasicSerializerFactory不能       访问一个类的成员       带修饰符的com.fasterxml.jackson.databind.ser.std.NullSerializer       "私人"

我的控制器转到服务方法,可以获取文件的路径。

function downloadDocument  ()  {

    var docName = $('.sampleFile').text();
    var questionType = $('#questionType').val();
    var questionLanguage = $('#questionLanguage').val();
    alert(docName);
    $.ajax({
        url : "downloadSample",
        async : false,
        type : "GET",
        data : "documentName" : docName ,
        contentType : "application/json;charset=UTF-8",
        dataType : "json",
        success : function(data){
            alert(data);
        }
    });

}  

Spring控制器是:

@RequestMapping(value = "/downloadSample", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public void sampleFileDownload( @RequestParam(value = "documentName") String documentName) {

    String realPath = context.getRealPath("") + "static" + File.separator + "sampleFile" + File.separator + questionType + File.separator + questionLanguage + File.separator + documentName;

    try {
        File file = new File(realPath);
        logger.debug("REal path in sample Document " + realPath);
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        String mimeType = URLConnection.guessContentTypeFromStream(inputStream);
        if (mimeType == null) {
            mimeType = "application/octet-strem";
        }
        response.setContentType(mimeType);
        response.setContentLength((int) file.length());
        response.setHeader("Content-Diposition", String.format("attachement; filename=\"%s\"", file.getName()));

        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

尽快给出解决方案。

0 个答案:

没有答案