基于springboot的文件上传和下载

JAVA代码:

​
/**文件的上传和下载**/
@RestController
public class FileUpAndDownController {
    // 上传文件
    @PostMapping("/fileUpload")
    public  ResponseEntity<?> handleFileUpload(@RequestParam("file") MultipartFile file) {
      
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty");
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get("src/main/resources/static/File" + File.separator + file.getOriginalFilename());
            Files.write(path, bytes);

            return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Could not upload the file: " + e.getMessage());
        }
    }

    // 下载文件
    @GetMapping("/fileDownload")
    public ResponseEntity<?> downloadFile(HttpServletRequest request,@RequestParam("filename") String filename) {
        try {
            File file = new File("src/main/resources/static/File"+ File.separator +filename);
            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            byte[] bytes = new byte[(int) file.length()];
            FileInputStream fis = new FileInputStream(file);
            fis.read(bytes);
            fis.close();
            filename=getFilename(request, filename);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=" + filename);
            headers.setContentDispositionFormData("attachment",filename);
            //定义以流的形式下载返回文件数据
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    // 这个东西很重要!!!!
    // 如果不对文件名编码进行处理,会导致浏览器下载的文件不对版,还没扩展名

    //根据浏览器的不同进行编码设置,返回编码后的文件名
    private String getFilename(HttpServletRequest request, String filename)
            throws Exception {
        //IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        //获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器,统一为UTF-8编码显示,并对转换的+进行更正
                return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
            }}
        //火狐等其他浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }

}

​

前端测试代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传下载</title>
</head>
<body>
    <h1>文件上传</h1>  
    <form action="http://127.0.0.1:8080/fileUpload" method="post" enctype="multipart/form-data">  
        <input type="file" name="file" required />  
        <button type="submit">上传</button>  
    </form>  

    
    <h2>下载文件</h2>  
    <form action="http://127.0.0.1:8080/fileDownload" method="get">  
        <input type="text" name="filename" placeholder="输入文件名" required />  
        <button type="submit">下载</button>  
    </form>  
<script>
   
</script>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值