浏览器下载文件

示例代码:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

@RestController
@RequestMapping("/files")
public class DownloadController {

    /**
     * 根据文件名下载文件
     * 浏览器访问:http://localhost:9090/changyong/files/download?filename=file.txt //changyong为应用上下文,没有配置则可以不用
     *
     * @param fileName
     * @return
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam("filename") String fileName) throws IOException {
        //使用字节输入流加载文件进内存,这里的文件存放在resources目录下
        InputStream fis = this.getClass().getResourceAsStream("/" + fileName);
        if (Objects.isNull(fis)) {
            throw new FileNotFoundException("找不到" + fileName);
        }
        //设置response响应头
        String mimeType = request.getServletContext().getMimeType(fileName); //获取mime类型
        response.setHeader("content-type", mimeType); //设置响应头类型
        //如果下载的文件包含中文名,则需要使用 URLEncoder.encode(fileName, "UTF-8")对文件名称进行处理
        response.setHeader("content-disposition", "attachment;filename=" + fileName);  //设置响应头打开方式

        //将输入流的事件写出到输出事件
        OutputStream sos = response.getOutputStream();
        byte[] buffer = new byte[1024 * 8];
        int length = 0;
        while ((length = fis.read(buffer)) != -1) {
            sos.write(buffer, 0, length);
        }
        sos.flush();
        sos.close();
    }
}

 

posted @ 2022-06-07 12:01  残城碎梦  阅读(157)  评论(0编辑  收藏  举报