SpringBoot 上传和下载文件

SpringBoot 上传和下载文件,第1张

SpringBoot 上传和下载文件
package Controller;

import jdk.internal.loader.FileURLMapper;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/file")
public class FileHandler {
    @RequestMapping("/upload")
    public String upload(MultipartFile img, HttpServletRequest request) {
        if (img.getSize() > 0) {
            //获取保存上传文件的file路径
            String path = request.getServletContext().getRealPath("file");
            //获取上传的文件名
            String name = img.getOriginalFilename();
            String filePath = "D:\Work\Java\SpringMVC\src\main\webapp";
            File file = new File(filePath, name);
            try {
                img.transferTo(file);
                //保存上传之后的文件路径
                request.setAttribute("path", filePath + "\" + name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "upload";
    }

    @GetMapping("/download/{name}")
    public void download(@PathVariable("name") String name, HttpServletRequest request, HttpServletResponse response) {
        if(name != null) {
            name += ".png";
            String path = request.getServletContext().getRealPath("file");
            File file = new File(path, name);
            OutputStream outputStream = null;
            if(file.exists()) {
                response.setContentType("application/forc-download");
                response.setHeader("Content-Disposition", "attachment;filename="+name);
                try {
                    outputStream = response.getOutputStream();
                    outputStream.write(FileUtils.readFileToByteArray(file));
                    outputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5660432.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存