小言_互联网的博客

springBoot文件上传下载

385人阅读  评论(0)

springBoot文件上传下载

  • springboot项目,前台页面使用的thymeleaf模板
  • 前台页面resource下 templates/fileView.html,其中包含单个上传,下载,批量上传。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>单文件上传</p>
<!--action 依据自建项目路径调整-->
<form action="file/upload" method="POST" enctype="multipart/form-data">
    文件:<input type="file" name="file"/>
    <input type="submit" value="提交"/>
</form>
<hr/>
<p>文件下载</p>
<a href="file/download">下载文件</a>
<hr/>
<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data" action="file/batch">
    <p>文件1:<input type="file" name="file"/></p>
    <p>文件2:<input type="file" name="file"/></p>
    <p><input type="submit" value="上传"/></p>
</form>
</body>
</html>
  • ToFileViewController 用来跳转页面
@Controller
public class ToFileViewController {

    @RequestMapping("/fileView")
    public String index()
    {
        return "fileView";
    }
}
  • 本文的重点,FileController,其中包含单个上传,单个下载,批量上传对应的方法。需要注意下载功能写的是对应我电脑里面固定位置的文件,仅供大家来参考。以下是代码
/**
 * @Description  包含单个上传,单个下载,批量上传对应的方法。注意下载功能写的是对应我电脑里面固定位置的文件,仅供参考学习
 * @Author 
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2019-09-26
 */
@Api(value = "file", description = "文件处理案例")
@RestController
@RequestMapping("/file")
@Slf4j
@Validated
public class FileController {

    //单个上传
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if(file.isEmpty()){
                return "文件为空";
            }
            //获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileName);
            //获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("文件的后缀名为:" + suffixName);
            //设置文件的存储路径
            String filePath = "E:/kaifa/ieda/idea_workspace/logs";
            //拼接完整的文件路径
            String path = filePath +"/"+fileName;
            //构造文件对象
            File dest = new File(path);  //
            //检测是否存在目录(不存在新疆文件,存在直接写入文件)
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs(); //新建文件夹
            }
            //文件写入
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    @PostMapping("/batch")
    public String handleFileUpload(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);
            String filePath = "E:/kaifa/ieda/idea_workspace/logs";
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(
                            new FileOutputStream(
                                    new File(filePath + "/" + file.getOriginalFilename())));//设置文件路径及名字
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "第 " + i + " 个文件上传失败 ==> "
                            + e.getMessage();
                }
            } else {
                return "第 " + i
                        + " 个文件上传失败因为文件为空";
            }
        }
        return "上传成功";
    }

    @GetMapping("download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response){
        String fileName = "llfc.jpg"; // 测试文件名
        String realPath = "E:/kaifa/ieda/idea_workspace/logs";
        if(fileName != null){
            //设置文件路径
            File file = new File(realPath,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{
                  if(bis != null){
                      try {
                          bis.close();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                  }
                  if(fis != null){
                      try {
                          fis.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
                }
            }
        }
        return "下载失败";
    }
}

转载:https://blog.csdn.net/weixin_43854141/article/details/101627895
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场