Java教程

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)

 

 

 

这篇关于Java 浏览器文件下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!