日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

SpringMVC 使用RestFul風格實現簡單的文件下載

作者:weixin_44953227 更新時間: 2022-04-09 編程語言

配置文件

SpringMVC 配置和依賴:http://www.shdianci.com/article/6537.html


文件下載的 Controller

注意:restFul 風格一般會把文件后綴名截取掉, 加上 :.+ 來保留文件后綴名

package com.pro.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@RestController
public class FileController {

	// 使用restFul風格一般會把文件后綴名截取掉, 加上:.+ 來保留文件后綴名
    @RequestMapping(value = "/download/{fileName:.+}")
    public String download(@PathVariable String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
        System.out.println("download --> " + fileName);
        //要下載的圖片地址
        String path = request.getServletContext().getRealPath("/upload");

		File file = new File(path, fileName);
		if (!file.exists()) {
            return "文件不存在";
        }

        //1、設置response 響應頭
        response.reset(); //設置頁面不緩存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符編碼
        response.setContentType("multipart/form-data"); //二進制傳輸數據
        //設置響應頭
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        //2、 讀取文件--輸入流
        InputStream input = new FileInputStream(file);
        //3、 寫出文件--輸出流
        OutputStream out = response.getOutputStream();

        //4、執行 寫出操作
        byte[] buff = new byte[1024];
        int index = 0;
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }

        // 關閉流
        out.close();
        input.close();
        return null;
    }
}

測試

啟動項目訪問:http://localhost:8080/download/xxx.xx

我的項目中有一個 aa.pdf 的文件, 就直接訪問

http://localhost:8080/download/aa.pdf


原文鏈接:https://blog.csdn.net/weixin_44953227/article/details/113479130

欄目分類
最近更新