1. 程式人生 > 其它 >Java 瀏覽器檔案下載

Java 瀏覽器檔案下載

1.在pom.xml檔案中新增JSON依賴

 <!-- 阿里fastjson包JSON轉換-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

2.具體程式碼

(1)controller層

 @RequestMapping(value = "downloadFile", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value 
= "瀏覽器下載檔案") public void downloadFile(HttpServletResponse response){ try { uploadService.download(response); } catch (Exception e) { e.printStackTrace(); } }

(2)Service層

import com.alibaba.fastjson.JSON;
import com.example.demo.util.Result;
import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.HashMap; import java.util.Map; @Service @Slf4j public class UploadService { @SneakyThrows public void
download(HttpServletResponse response) { try { String path = null; String filePath = System.getProperty("user.dir")+ File.separator+"doc"+File.separator+"匯出模板"; String fileName = "標籤模板.xlsx"; path = filePath + File.separator + fileName; File file = new File(path); //String filename = file.getName();// 取得檔名。 //String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();// 取得檔案的字尾名。 // 以流的形式下載檔案 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); // 清空response response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.substring(0,fileName.indexOf(".")).getBytes("gbk"), "iso8859-1") + ".xlsx"); // 設定response的Header response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException e) { // 重置response response.reset(); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); Map<String, String> map = new HashMap<String, String>(); map.put("status", "failure"); map.put("message", "下載檔案失敗" + e.getMessage()); Result result = Result.newResponse(200, JSON.toJSONString(map)); response.getWriter().println(JSON.toJSONString(result)); } } }

(3)Result:封裝response

package com.example.demo.util;

import com.github.pagehelper.PageInfo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 封裝response
 */
public class Result<T> {
    private int code = 0;
    private String msg;
    private T data;

    public int getCode() {
        return this.code;
    }

    public String getMsg() {
        return this.msg;
    }

    public T getData() {
        return this.data;
    }

    private Result(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    protected Result() {
    }

    public static Result newResponse(int code, String msg, String data) {
        return new Result(code, msg, data);
    }

    public static Result newResponse(int code, String msg, PageInfo data) {
        return new Result(code, msg, data);
    }
    public static Result newResponse(int code, String msg, List data) {
        return new Result(code, msg, data);
    }

    public static Result newResponse(int code, String msg, Map data) {
        return new Result(code, msg, data);
    }
    public static Result newResponse(int code, String msg, Object data) {
        return new Result(code, msg, data);
    }

    public static Result newResponse(int code, String msg) {
        return newResponse(code, msg, new HashMap(16));
    }

    public static Result newResponse(String statusExpression, String data) {
        String[] fields = statusExpression.split("\\|");
        return newResponse(Integer.parseInt(fields[0].trim()), fields.length > 1 ? fields[1].trim() : "", data);
    }

    public static Result newResponse(String statusExpression, List data) {
        String[] fields = statusExpression.split("\\|");
        return newResponse(Integer.parseInt(fields[0].trim()), fields.length > 1 ? fields[1].trim() : "", data);
    }

    public static Result newResponse(String statusExpression, Map data) {
        String[] fields = statusExpression.split("\\|");
        return newResponse(Integer.parseInt(fields[0].trim()), fields.length > 1 ? fields[1].trim() : "", data);
    }

    public static Result newResponse(String statusExpression, Object data) {
        String[] fields = statusExpression.split("\\|");
        return newResponse(Integer.parseInt(fields[0].trim()), fields.length > 1 ? fields[1].trim() : "", data);
    }

    public static Result newResponse(String statusExpression) {
        return newResponse(statusExpression, new HashMap(16));
    }

    public static Result newResponse() {
        return newResponse("0|成功");
    }

    public static Result newResponse(Map data) {
        return newResponse("0|成功", data);
    }

    public static Result forwardErrorResponse(Result response) {
        return response.getCode() == 0 ? null : response;
    }

    public Result format(Object... args) {
        this.msg = String.format(this.msg, args);
        return this;
    }

    public static String formatRawResponse(int code, String msg, String data) {
        return String.format("{\"code\": %d, \"msg\": \"%s\", \"data\": %s}", code, msg, data);
    }

    public static String formatRawResponse(String statusExpression, String data) {
        String[] fields = statusExpression.split("\\|");
        return formatRawResponse(Integer.parseInt(fields[0].trim()), fields[1].trim(), data);
    }

    public static String formatRawResponse(String data) {
        return formatRawResponse("0|成功", data);
    }

    public boolean isSuccess() {
        return this.getCode() == 200;
    }
}

3.在專案路徑下新增doc與匯出模板資料夾,並將需要下載的檔案放在匯出模板資料夾下,如下圖所示:

4.在瀏覽器上輸入訪問路徑即可下載該檔案(http://localhost:埠號/file/downloadFile)