Java下載文件

文件下載小技巧:
由于不能使用ajax直接下載文件,因此要做到無刷新頁面下載,可以采用以下方案:
1.使用ajax提交生成臨時文件存放到服務器,并返回文件名(建議文件路徑放置在指定的目錄下,只返回文件名即可,全文件名需要js文件中做轉碼)
2.根據(jù)返回結果,發(fā)送下載請求,參數(shù):文件名

JS(前端采用layui),返回json格式: {"message":"測試導出數(shù)據(jù).xlsx","result":true}

我們提供的服務有:網(wǎng)站設計制作、網(wǎng)站制作、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、左貢ssl等。為上1000家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術的左貢網(wǎng)站制作公司

// 下載文件
$("#exportExt").on("click",function(){
  // 友好提示信息
    var msgIndex = layer.msg('數(shù)據(jù)下載中,由于數(shù)據(jù)較大,請耐心等候...11', {icon: 16,scrollbar: false,time: 0});
    $.ajax({
            type : 'post',
            async : false, // 默認異步true,false表示同步
            url : 'exp/createExpFile', // 生成文件,保存在服務器
            dataType : 'json', // 服務器返回數(shù)據(jù)類型
            data : {
                startDate : $("#startDate").val(),
                endDate : $("#endDate").val()
            },
            success : function(data) {
              // 關閉提示信息
              layer.close(msgIndex);
              if(data.result == true) {
                    window.location.href='test/downLoad?fileName=' + data.message;
              } 
            },
            error : function(XMLHttpRequest, textStatus, e) {
                    // 關閉提示信息
                layer.close(msgIndex);
                layer.alert('導出數(shù)據(jù)失敗', {icon: 5});
            }
    });
});

Controller

@Autowired
TestService testService;
/**
 * @描述: 生成下載文件
 * @return
 * @日期 2019年6月20日
 */
@RequestMapping("createExpFile")
@ResponseBody
public String createExpFile(){
    return testService.createExpFile();
}

/**
 * @描述: 導出下載文件
 * @日期 2019年6月20日
 */
@RequestMapping("downLoadExt")
@ResponseBody
public void downLoadExt(){
    testService.downLoadExt();
}

Service
下載文件請參考java導出數(shù)據(jù)到Excel文件

@Autowired
public HttpServletResponse response;
// 臨時文件目錄,這里指定一個目錄,實際應用建議動態(tài)獲取目錄
private static final String tempPath = "e:"+ "tempFile" + File.separator + "download" + File.separator;
/**
 * @描述: 生成下載文件
 * @return
 * @日期 2019年6月20日
 */
public String createExpFile() {
  // 文件存放目錄
    String savePath = tempPath;
    // 文件存放名稱
    String fileName = "測試下載文件.xlsx";
    // 1.獲取要導出的數(shù)據(jù)信息
    List<String[]> dataList = getDownLoadData();
    // 2.導出信息到Excel文件(參考https://blog.51cto.com/blogger/publish/2411391)
    boolean expFlag = ToolExcelExp.exportBigDataExcel(savePath + fileName, dataList);

    MessageBean messageBean = new MessageBean();
    messageBean.setResult(expFlag);
    messageBean.setMessage(fileName);

    return JSONObject.toJSONString(messageBean);
}

/**
 * @描述: 導出下載文件
 * @日期 2019年6月20日
 */
public void downLoadExt() {
    Map<String, Object> paramMaps = getMaps();
    // 文件存放目錄
    String savePath = tempPath;
    // 文件存放名稱
    String fileName = paramMaps.get("fileName").toString();
    // 文件下載
    ToolDownLoad.downloadFile(response, savePath + fileName);
    System.out.println("導出完畢");
}

文件下載工具類

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

public class ToolDownLoad {
    /**
     * @描述: 文件下載
     * @param response
     * @param filePath 要下載的文件全路徑
     * @日期 2019年6月19日
     */
    public static void downloadFile(HttpServletResponse response, String filePath) {
        response.setContentType("text/html;charset=utf-8");
        System.out.println(filePath);
        File file = new File(filePath);
        String fileName = file.getName();
        long fileLength = file.length();
        if (file.exists()) {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                response.setContentType("application/force-download");// 設置強制下載不打開
                response.addHeader("Content-Disposition", "attachment; fileName=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));// 設置文件名
                response.setHeader("Content-Length", String.valueOf(fileLength));
                byte[] buffer = new byte[1024];
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 下載完畢,刪除文件
                file.delete();
            }
        }
    }
}

新聞名稱:Java下載文件
新聞來源:http://bm7419.com/article14/gihhge.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設軟件開發(fā)、用戶體驗、做網(wǎng)站、ChatGPT、網(wǎng)站排名

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)