javascript - 下载文件并将其保存在浏览器的本地存储中

标签 javascript ajax spring-mvc download local-storage

我有一个提供文件服务的 Java 网络应用程序:

@RequestMapping(value = "/pdf/download", method = RequestMethod.GET)
public void download(
        HttpServletRequest request, 
        HttpServletResponse response, 
        @RequestParam(value = "id", required = true) Long id) throws IOException {

    File pdfFile = pdfFileManager.getFromId(id);

    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=download");
    response.setContentLength((int) pdfFile.length());

    FileInputStream fileInputStream = null;
    OutputStream responseOutputStream = null;

    try {   
        fileInputStream = new FileInputStream(pdfFile);
        responseOutputStream = response.getOutputStream();

        int bytes;
        while ((bytes = fileInputStream.read()) != -1) {
            responseOutputStream.write(bytes);
        }

        responseOutputStream.flush();
    } finally {
        fileInputStream.close();
        responseOutputStream.close();
    }
}

我在客户端检索文件并使用 FileReader 对其进行 base64 编码:

$.ajax({
    url: "/pdf/download?id=" + id,
    dataType: "application/pdf",
    processData: false
}).always(function(response) {
    if(response.status && response.status === 200) {
       savePdf(response.responseText, "download_" + id);
    } 
}); 

function savePdf(pdf, key) {
    var blob = new Blob([pdf], {type: "application/pdf"});
    var fileReader = new FileReader();

    fileReader.onload = function (evt) {
        var result = evt.target.result;

        try {
            localStorage.setItem(key, result);
        } catch (e) {
            console.log("Storage failed: " + e);
        }
    };

    fileReader.readAsDataURL(blob);
}

问题是本地存储中保存的值不正确。编码数据与我使用 this snip 上传 PDF 时得到的数据不同。 .我不知道问题是我如何在客户端提供文件或编码过程。

存储的值是这样的

data:application/pdf;base64,JVBERi0xLjQKJe+/ve+/ve+/ve+/vQoxIDAgb...

代替

data:application/pdf;base64,JVBERi0xLjQKJeHp69MKMSAwIG9iago8PC9Ue...

最佳答案

解决了将请求的响应类型设置为 blob 的问题:

var xhr = new XMLHttpRequest(); 
xhr.open("GET", "/pdf/download?id=" + id); 
xhr.responseType = "blob";
xhr.onload = function() {
    if(xhr.status && xhr.status === 200) {
        savePdf(xhr.response, "download_" + id);
    } 
}
xhr.send();

function savePdf(pdf, key) {
    var fileReader = new FileReader();

    fileReader.onload = function (evt) {
        var result = evt.target.result;

        try {
            localStorage.setItem(key, result);
        } catch (e) {
            console.log("Storage failed: " + e);
        }
    };

    fileReader.readAsDataURL(pdf);
}

关于javascript - 下载文件并将其保存在浏览器的本地存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33760075/

相关文章:

javascript - 元素随机移动到列表上预先确定的位置

jquery - 如何添加图像上传以及ajax jquery表单提交

java - Tomcat v9.0 无法启动 - org.apache.catalina.LifecycleException : Failed to initialize component

java - 处理状态为 NO_CONTENT 的响应时的 Spring RestTemplate 行为

javascript - 如何在 IE8 的 javascript 中选择 DOM 节点?

javascript - 在 Angular 中的文件对话框之前允许模态对话框

javascript - after() 与 fadein() jquery 不工作

php - 使用 Codeigniter 使用 AJAX 和 jquery 将表单数据传递给 Controller

javascript - 将 JSON 数据从 View 传递到 Controller 为 null

java - BeanValidation 错误 - 在类路径上找不到 JSR 303 Bean 验证实现