java实现简易文件下载

文件下载工具类:

package com.cms.common.utils;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

public class DownUtil {
    //下载模版工具类
    public static ResponseEntity<Object> downloadFile(HttpServletRequest request,
                                                      HttpServletResponse response, String fileName, String url) throws Exception {
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            File f = new File(url);
            response.setHeader("Accept-Ranges", "bytes");
            //设置文件下载是以附件的形式下载
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", new String(fileName.getBytes(),"ISO-8859-1")));
            response.setHeader("Content-Length",String.valueOf(f.length()));
            in = new BufferedInputStream(new FileInputStream(f));
            out = new BufferedOutputStream(response.getOutputStream());
            byte[] data = new byte[1024];
            int len = 0;
            while (-1 != (len=in.read(data, 0, data.length))) {
                out.write(data, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
        return new ResponseEntity<Object>(HttpStatus.OK);
    }
}

Controller:

	@RequestMapping("/download")
	public ResponseEntity<Object> download(HttpServletRequest request, HttpServletResponse response, String url, String fileName) throws Exception {
		String path = request.getServletContext().getRealPath("/");
		url = url.replace("uploadimgs", "upload");
		path = path+url;
		return DownUtil.downloadFile(request,response,fileName,path);
	}

猜你喜欢

转载自blog.csdn.net/w_dongqiang/article/details/80196925
今日推荐