转载

从零搭建自己的SpringBoot后台框架(十六)

Hello大家好,本章我们添加多文件上传功能 。有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢

在一个系统中,文件上传模块肯定是少不了的,例如头像上传,展示轮播图等等,所以本章我们来添加上传文件功能

一:添加commons-fileupload依赖

打开pom文件添加

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
</dependency>

二:添加系统变量

打开core→constant文件,添加文件保存路径

//文件上传储存的地址
public static final String SAVEFILEPATH = "F://img";

三:添加文件上传限制

创建core→configurer→MultipartConfigurer.java

package com.example.demo.core.configurer;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.MultipartConfigElement;

@Configuration
public class MultipartConfigurer {

    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory=new MultipartConfigFactory();
        factory.setMaxFileSize("10MB");
        factory.setMaxRequestSize("10MB");
        return factory.createMultipartConfig();
    }
}

四:创建文件上传工具类

创建core→utils→UploadActionUtil.java

package com.example.demo.core.utils;

import com.example.demo.core.constant.ProjectConstant;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 张瑶
 * 文件上传控制器
 */
public class UploadActionUtil {

   public static List<String> uploadFile(HttpServletRequest request) throws Exception {
      List<String> list = new ArrayList<>();
      CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
      if (multipartResolver.isMultipart(request)) {
         MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
         Iterator<String> iterator = multiRequest.getFileNames();
         while (iterator.hasNext()) {
            // 取得上传文件
            MultipartFile file = multiRequest.getFile(iterator.next());
            if (file != null) {
               // 取得当前上传文件的文件名称
               String myFileName = file.getOriginalFilename();
               // 如果名称不为“”,说明该文件存在,否则说明该文件不存在
               if (myFileName.trim() != "") {
                  String fileTyps = myFileName.substring(myFileName.lastIndexOf("."));
                  // String tempName="demo"+fileTyps;
                  String tempName = UUID.randomUUID().toString() + fileTyps;
                  // 创建文件夹
                  String folderPath = ProjectConstant.SAVEFILEPATH + File.separator + folderName();
                  File fileFolder = new File(folderPath);
                  if (!fileFolder.exists() && !fileFolder.isDirectory()) {
                     fileFolder.mkdir();
                  }
                  File uploadFile = new File(folderPath + File.separator + tempName);
                  file.transferTo(uploadFile);
                  myFileName = folderName() + File.separator + tempName;
                  list.add(ProjectConstant.SAVEFILEPATH + "//" + myFileName);
               }
            }
         }
      }
      return list;
   }

   /**
    * 得年月日的文件夹名称
    * 
    * @return
    */
   public static String getCurrentFilderName()  throws Exception{
      Calendar now = Calendar.getInstance();
      return now.get(Calendar.YEAR) + "" + (now.get(Calendar.MONTH) + 1) + "" + now.get(Calendar.DAY_OF_MONTH);
   }

   /**
    * 创建文件夹
    * 
    * @param filderName
    */
   public static void createFilder(String filderName) throws Exception {
      File file = new File(filderName);
      // 如果文件夹不存在则创建
      if (!file.exists() && !file.isDirectory()) {
         file.mkdirs();
      }
   }

   /**
    * 文件扩展名
    * 
    * @param fileName
    * @return
    */
   public static String extFile(String fileName)  throws Exception{
      return fileName.substring(fileName.lastIndexOf("."));
   }

   /**
    * 当前日期当文件夹名
    * 
    * @return
    */
   public static String folderName() throws Exception {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
      String str = sdf.format(new Date());
      return str;
   }
}

五:创建UploadFileController

package com.example.demo.controller;

import com.example.demo.core.ret.RetResponse;
import com.example.demo.core.ret.RetResult;
import com.example.demo.core.utils.UploadActionUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/uploadFile")
public class UploadFileController {

    @PostMapping("/upload")
    public RetResult<List<String>> upload(HttpServletRequest httpServletRequest) throws Exception {
        List<String> list = UploadActionUtil.uploadFile(httpServletRequest);
        return RetResponse.makeOKRsp(list);
    }
}

六:测试

打开postman

输入localhost:8080/uploadFile/upload

注意:请求参数如下

从零搭建自己的SpringBoot后台框架(十六)

返回值为文件存储的路径

打开设置好的存储路径

从零搭建自己的SpringBoot后台框架(十六)

ok,上传成功

项目地址

gitee.com/beany/mySpr…

写文章不易,如对您有帮助,请帮忙点下star 从零搭建自己的SpringBoot后台框架(十六)

结尾

添加多文件上传功能已完成,后续功能接下来陆续更新,有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢大家。

原文  https://juejin.im/post/5b0d3ac9f265da08de1f555e
正文到此结束
Loading...