Ajax文件下載問(wèn)題

一、Ajax文件下載問(wèn)題還原

1、前端代碼

$(".delbtn").click(function () {
    var _this = $(this);
    // 文件id
    var _this_file_id = _this.attr('name');

    if (!_this_file_id || _this_file_id < 1) {
        return false;
    }

    debugger

    $.ajax({
        url: '/pc/download/file',
        data: {fileResourceId : _this_file_id},
        type: "POST",
        success: function() {

        },
        error: function () {

        }
    });

    // window.location.href = _this_url;
});

2、后天代碼

package com.antscity.fsm.site.controller.pc;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.antscity.common.util.StringUtil;
import com.antscity.fsm.base.model.wechat.LoginMember;
import com.antscity.kernel.base.model.common.AliyunOssProperties;
import com.antscity.kernel.base.model.common.FileResource;
import com.antscity.kernel.base.service.common.FileResourceService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * 文件下載服務(wù)
 */

@Controller
@RequestMapping("/pc/download/")
public class DownloadController {

    @Autowired
    private AliyunOssProperties ossProperties;

    @Reference
    private FileResourceService fileResourceService;

    /**
     * 文件下載
     *
     * @param fileResourceId
     * @param loginMember
     * @param response
     */
    @RequestMapping(value = "file", method = RequestMethod.POST)
    public void getFile(
            Long fileResourceId, LoginMember loginMember,
            HttpServletResponse response, HttpServletRequest request) throws IOException{

        Long tenantId = loginMember.getTenantId();

        FileResource fileResource = fileResourceService.findById(tenantId, fileResourceId);

        if (Objects.isNull(fileResource)) return;

        String url = fileResource.getUrl();

        byte[] bytes;

        try {
            bytes = getOssFileByteArray(url);
        } catch (OSSException | ClientException e) {
            bytes = getUrlFileByteArray(url);
        }

        if (Objects.isNull(bytes)) return;

        String fileName = getFileName(fileResource);

        this.writeFileByteArray(response, bytes, fileName);
    }

    @RequestMapping(value = {"/fileByUrl"}, method = {RequestMethod.POST})
    public void getFileByUrl(
            String fileUrl, LoginMember loginMember,
            HttpServletResponse response, HttpServletRequest request ) throws IOException {

        byte[] bytes;
        try {
            bytes = getOssFileByteArray(fileUrl.split("&")[0]);
        } catch (OSSException | ClientException e) {
            bytes = getUrlFileByteArray(fileUrl.split("&")[0]);
        }
        if (Objects.isNull(bytes)) return;
        this.writeFileByteArray(response, bytes, fileUrl.split("&")[1]);
    }

    /**
     * 用OSSClient獲取文件字節(jié)
     */
    private byte[] getOssFileByteArray(String url) throws IOException {
        OSSClient ossClient = new OSSClient(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret());
        try {
            int keyBeginIndex = url.lastIndexOf("/", url.lastIndexOf("/") - 1) + 1;

            String key = url.substring(keyBeginIndex, url.length());

            GetObjectRequest objectRequest = new GetObjectRequest(ossProperties.getBucketName(), key);

            OSSObject ossObject = ossClient.getObject(objectRequest);

            return this.getFileByteArray(ossObject.getObjectContent());

        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 用url獲取文件字節(jié)
     */
    private byte[] getUrlFileByteArray(String url) throws IOException {

        URL urlObject = new URL(url);

        return this.getFileByteArray(urlObject.openStream());
    }

    /**
     * 獲取到真正的下載文件名
     */
    private String getFileName(FileResource fileResource) {
        String nameOrUrl = StringUtil.isEmpty(fileResource.getFileName()) ?
                fileResource.getUrl() :
                fileResource.getFileName();

        int nameBeginIndex = nameOrUrl.lastIndexOf("/") + 1;

        return nameOrUrl.substring(nameBeginIndex, nameOrUrl.length());
    }

    /**
     * 向response中寫(xiě)入文件字節(jié)
     */
    private void writeFileByteArray(HttpServletResponse response, byte[] bytes, String fileName) throws IOException {
        response.setContentType("application/octet-stream");

        response.setHeader("Cache-Control", "no-store");

        response.setHeader("Pragma", "no-cache");

        response.setDateHeader("Expires", 0);

        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        response.setContentLength(bytes.length);

        ServletOutputStream outputStream = response.getOutputStream();

        outputStream.write(bytes);

        outputStream.flush();
    }

    /**
     * 從輸出流中讀取到文件所有的字節(jié)
     */
    private byte[] getFileByteArray(InputStream inputStream) throws IOException {

        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();

        byte[] buff = new byte[1024];

        int rc = 0;

        while ((rc = inputStream.read(buff, 0, 1024)) > 0) {
            swapStream.write(buff, 0, rc);
        }

        swapStream.close();

        inputStream.close();

        return swapStream.toByteArray();
    }
}

3、結(jié)果展示

  • PC沒(méi)有展示下載信息,響應(yīng)頭正確,數(shù)據(jù)也正確的傳到后臺(tái),當(dāng)查看請(qǐng)求結(jié)果時(shí)(F12 NetWork),發(fā)現(xiàn)為亂碼的字節(jié)串

二、解決

1、基本方法

不適用Ajax請(qǐng)求方式,使用get直接請(qǐng)求,后臺(tái)代碼不變

$(".delbtn").click(function () {
    var _this = $(this);
    var _this_file_id = _this.attr('name');

    if (!_this_file_id || _this_file_id < 1) {
        return false;
    }

    window.location.href = "/pc/download/file?fileResourceId=" + _this_file_id;
});

2、其他方式參考

https://www.cnblogs.com/qlqwjy/p/8971207.html

https://www.cnblogs.com/nuccch/p/7151228.html

三、總結(jié)原因

  • 驗(yàn)證:ajax方式下載文件時(shí)無(wú)法觸發(fā)瀏覽器打開(kāi)保存文件對(duì)話框,也就無(wú)法將下載的文件保存到硬盤(pán)上!

  • 原因:ajax方式請(qǐng)求的數(shù)據(jù)只能存放在javascipt內(nèi)存空間,可以通過(guò)javascript訪問(wèn),但是無(wú)法保存到硬盤(pán),因?yàn)閖avascript不能直接和硬盤(pán)交互,否則將是一個(gè)安全問(wèn)題。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容