Springboot上传与下载文件

  • application.yml
  #设置静态资源路径
  resources:
    static-locations: classpath:static/,file:static/
    #文件大小
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  • Springboot上传文件(单个文件)

           uploadImg.html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="keywords" content="keyword1,keyword2,keyword3"/>
    <meta name="description" content="this is my page"/>
    <meta name="content-type" content="text/html; charset=UTF-8"/>
    <title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/uploadImg">
    文件:<input type="file" name="file"/>
    <input type="submit" value="上传"/>
</form>
</body>
</html>

     UploadImgController文件: 

 /**
     * 上传单个文件
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadImg")
    @ResponseBody
    public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request)throws Exception{
        if(file.isEmpty()){
            return "请选择文件上传";
        }
       String contentType = file.getContentType();
       String fileName = file.getOriginalFilename();
//        String filePath = "D:\\fileupload\\";//固定保存路径
     //  String filePath = request.getSession().getServletContext().getRealPath("/imgupload");
       //log.info("filepath="+ClassUtils.getDefaultClassLoader().getResource("").getPath());//输出: F:/tonglingling/springbootDemo1/target/classes/

        try {
            File path=new File(ResourceUtils.getURL("classpath:").getPath());
            File targetFile=new File(path.getAbsolutePath(),"static/fileupload/");//jar包下面的target目录
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            log.info("targer="+targetFile); // F:\tonglingling\springbootDemo1\target\classes\static\fileupload
            FileOutputStream out = new FileOutputStream(targetFile+"/"+fileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
         //   FileUtil.uploadFile(file.getBytes(),filePath,fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "uploadImg Success";
    }

 

  • Springboot上传文件(多个文件)
  •  /**
         * 批量上传图片
         * @param request
         * @return
         */
        @PostMapping("/batchImg")
        @ResponseBody
        public String batchImg(HttpServletRequest request){
            List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
            MultipartFile file = null;
            BufferedOutputStream stream = null;
            for(int i=0;i<files.size();i++){
                file = files.get(i);
                if(!file.isEmpty()){
                    try {
                        String fileName = file.getOriginalFilename();
                        File path=new File(ResourceUtils.getURL("classpath:").getPath());
                        File targetFile=new File(path.getAbsolutePath(),"static/imgupload/");//jar包下面的target目录
                        if(!targetFile.exists()){
                            targetFile.mkdirs();
                        }
                        byte[] bytes = file.getBytes();
                        stream = new BufferedOutputStream(new FileOutputStream(new File(targetFile+"/"+fileName)));
                        stream.write(bytes);
                        stream.close();
                    } catch (IOException e) {
                        stream = null;
                        e.printStackTrace();
                        return "上传失败"+i+"=>"+e.getMessage();
                    }
                }else{
                    return "文件为空";
                }
            }
            return "上传成功";
        }

     

  • Springboot下载文件
   /**
     * 下载文件
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/download")
    @ResponseBody
    public String download(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String fileName = "2.jpg";// 文件名
        if (fileName != null) {
            //设置文件路径
        //    String pathname = "D:\\fileupload\\1.jpg";
            File path=new File(ResourceUtils.getURL("classpath:").getPath());
            File targetFile=new File(path.getAbsolutePath(),"static/imgupload/");//jar包下面的target目录
            File file = new File(targetFile+"/"+fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    bis.close();
                    fis.close();
                }
            }else{
                return "文件不存在";
            }
        }
        return "下载失败";
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值