SpringBoot + vue 实现文件上传

原文地址 

https://blog.csdn.net/weixin_40879055/article/details/124758828

 

概述文件上传使用场景

  • 文件上传,是程序开发中必会用到的一个功能,比如

    1. 添加商品、用户头像、文章封面等
    2. 富文本编辑(插件文件上传)
  • 文件上传原理
    把本地文件上传到服务器,实现资源共享

SpringBoot实现本地文件上传

搭建后台接口
  1. 相关依赖
    <!--SpringMVC的启动器-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--用来处理文件上传的一个通用工具类-->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    <!--lombox插件-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    

      

  2. 文件上传相关配置
    在项目application.yml文件中配置文件上传相关的配置信息
    # 文件上传配置
    files:
      upload:
    #    path: D:/代码/小白做毕设2022/files/
        # 文件上传目标路径
        path: /Users/fangqi174956/Desktop/java/project/pure-design-master/files/
        # 文件上传允许的类型
        allowTypes:
          - image/jpeg
          - image/png
          - image/jpg
          - image/gif
          - text/html
          - text/css
          - application/msword
          - application/pdf
          - application/vnd.ms-excel
    

      

  3. 创建FileUploadProperties.java类
    读取application.yml文件中配置文件上传相关的配置信息
import java.util.List;

/**
 * 使用ConfigurationProperties将配置读取到Java文件中
 * @author fangqi174956
 */

@Data
@Component
@ConfigurationProperties(prefix = "files.upload")
public class FileUploadProperties {

    private String path;
    private List<String> allowTypes;

}

  

  1. 文件上传的配置类
    对上传文件的大小进行限制
    /**
     * 文件上传功能配置类
     * @author fangqi174956
     */
    
    @Configuration
    public class FileUploadConfig {
        /**   单个数据大小 10M  */
        private static final String SINGLE_FILE_SIZE = "10240KB";
        /** 总上传数据大小 100M */
        private static final String TOTAL_FILE_SIZE = "10240KB";
    
        @Bean
        public MultipartConfigElement multipartConfigElement() throws IOException {
            MultipartConfigFactory factory = new MultipartConfigFactory();
            factory.setMaxFileSize(DataSize.parse(SINGLE_FILE_SIZE));
            ///
            factory.setMaxRequestSize(DataSize.parse(TOTAL_FILE_SIZE));
            return factory.createMultipartConfig();
        }
    }
    

      

  2. 文件上传工具类
    import cn.hutool.core.date.DateUtil;
    import java.text.DecimalFormat;
    import java.util.Date;
    
    /**
     * 文件上传相关工具类
     * @author fangqi174956
     */
    public class FileUploadUtils {
    
        /**
         * 唯一ID生成器,可以生成唯一ID
         * @return
         */
        public static String generateUniqueId() {
            return DateUtil.format(new Date(),"yyyyMMdd") +System.currentTimeMillis();
        }
    
        /**
         * 文件名称替换工具,将文件名称替换为随机名称
         * @param oldName
         * @return
         */
        public static String generateFileName(String oldName){
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            return generateUniqueId()+suffix;
        }
    
        /**
         * 将文件大小转换成 KB MB GB
         * @param size
         * @return
         */
        public static String getNetFileSizeDescription(long size) {
            StringBuffer bytes = new StringBuffer();
            DecimalFormat format = new DecimalFormat("###.0");
            if (size >= 1024 * 1024 * 1024) {
                double i = (size / (1024.0 * 1024.0 * 1024.0));
                bytes.append(format.format(i)).append("GB");
            }
            else if (size >= 1024 * 1024) {
                double i = (size / (1024.0 * 1024.0));
                bytes.append(format.format(i)).append("MB");
            }
            else if (size >= 1024) {
                double i = (size / (1024.0));
                bytes.append(format.format(i)).append("KB");
            }
            else if (size < 1024) {
                if (size <= 0) {
                    bytes.append("0B");
                }
                else {
                    bytes.append((int) size).append("B");
                }
            }
            return bytes.toString();
        }
        
    }
    

      

  3. 新建文件上传接口 /upload
    • cotroller层
      import com.qingge.springboot.common.Result;
      import com.qingge.springboot.service.IFileUploadService;
      import org.springframework.web.bind.annotation.PostMapping;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestParam;
      import org.springframework.web.bind.annotation.RestController;
      import org.springframework.web.multipart.MultipartFile;
      
      import javax.annotation.Resource;
      
      /**
       * 文件上传管理控制器
       * @author fangqi174956
       */
      @RestController
      @RequestMapping("/files")
      public class FileUploadController {
      
          @Resource
          private IFileUploadService fileUploadService;
      
          @PostMapping("/upload")
          public Result upload(@RequestParam("file") MultipartFile file){
              try {
                  fileUploadService.uploadFile(file);
              } catch (Exception e) {
                  return Result.error("-1",e.getMessage());
              }
              return Result.success();
          }
      }
      

        

    • service层接口
      /**
       * 文件上传
       * @author fangqi174956
       */
      public interface IFileUploadService {
      
          /**
           * 上传文件
           * @param file
           * @return
           * @throws Exception
           */
          String uploadFile(MultipartFile file) throws Exception;
      }
      

        

    • service层实现
      import com.qingge.springboot.config.upload.FileUploadProperties;
      import com.qingge.springboot.entity.Files;
      import com.qingge.springboot.service.IFileService;
      import com.qingge.springboot.service.IFileUploadService;
      import com.qingge.springboot.utils.FileUploadUtils;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
      import org.springframework.web.multipart.MultipartFile;
      
      import javax.annotation.Resource;
      
      import java.io.File;
      import java.io.IOException;
      
      /**
       * @author fangqi174956
       */
      @Service
      public class FileUploadServiceImpl implements IFileUploadService {
          
          @Autowired
          private FileUploadProperties uploadProperties;
          @Resource
          private IFileService fileService;
      
          @Override
          public String uploadFile(MultipartFile file) throws IOException {
              if(!uploadProperties.getAllowTypes().contains(file.getContentType())){
                  throw new IOException("文件上传类型错误!");
              }
              String fileName = FileUploadUtils.generateFileName(file.getOriginalFilename());
              file.transferTo(new File(uploadProperties.getPath()+fileName));
      
              // 将新上传到文件信息存储到数据库
              Files newFile = new Files();
              newFile.setName(file.getOriginalFilename());
              String type = fileName.substring(fileName.indexOf(".")+1);
              newFile.setType(type);
              newFile.setSize(FileUploadUtils.getNetFileSizeDescription(file.getSize()));
              newFile.setUrl("http://localhost:9090/files/" + fileName);
              fileService.save(newFile);
              return fileName;
          }
      }
      

        

      前端页面
      • 使用常规html元素标签
        <input type="file" @change="getFile($event)">
        <input type="button" value="上传" @click="upload()">
        

          发送请求实现上传

        upload() {
        	this.request.post("/files/upload",this.formData).then(res => {
        		if (res.code == '200') {
        			console.log('新到文件名',res.data)
        			this.$message.success("文件上传成功")
        		}
        	});
        },
        getFile(event) {
        	let file = event.target.files[0];
        	let fileName = file.name;
        	let index = fileName.lastIndexOf(".");
        	let fileType = ['png','jpeg','jpg','jif','doc','pdf','xls']
        	if (index != -1) {
        		let suffix = fileName.substr(index + 1).toLowerCase();
        		if (fileType.includes(suffix)) {
        			this.formData.append("file",file);
        		}else {
        			this.$message.error("文件格式错误!请选择'png','jpeg','jpg','jif','doc','pdf','xls'格式的文件")
        		}
        	}
        },
        

          

      • 使用ElementUI 的上传组件
        <el-upload action="http://localhost:9090/files/upload" 
        		:show-file-list="false"
                :on-success="handleFileUploadSuccess" 
                style="display: inline-block">
        	<el-button type="primary" class="ml-5">
        		上传文件 <i class="el-icon-top"></i>
        	</el-button>
        </el-upload>
        

          

概述文件上传使用场景文件上传,是程序开发中必会用到的一个功能,比如
添加商品、用户头像、文章封面等富文本编辑(插件文件上传)文件上传原理把本地文件上传到服务器,实现资源共享
SpringBoot实现本地文件上传搭建后台接口相关依赖<!--SpringMVC的启动器--><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency><!--用来处理文件上传的一个通用工具类--><dependency>    <groupId>commons-io</groupId>    <artifactId>commons-io</artifactId>    <version>2.6</version></dependency><!--lombox插件--><dependency>    <groupId>org.projectlombok</groupId>    <artifactId>lombok</artifactId></dependency>
12345678910111213141516文件上传相关配置在项目application.yml文件中配置文件上传相关的配置信息# 文件上传配置files:  upload:#    path: D:/代码/小白做毕设2022/files/    # 文件上传目标路径    path: /Users/fangqi174956/Desktop/java/project/pure-design-master/files/    # 文件上传允许的类型    allowTypes:      - image/jpeg      - image/png      - image/jpg      - image/gif      - text/html      - text/css      - application/msword      - application/pdf      - application/vnd.ms-excel
1234567891011121314151617创建FileUploadProperties.java类读取application.yml文件中配置文件上传相关的配置信息import java.util.List;
/** * 使用ConfigurationProperties将配置读取到Java文件中 * @author fangqi174956 */
@Data@Component@ConfigurationProperties(prefix = "files.upload")public class FileUploadProperties {
    private String path;    private List<String> allowTypes;
}
12345678910111213141516文件上传的配置类对上传文件的大小进行限制/** * 文件上传功能配置类 * @author fangqi174956 */
@Configurationpublic class FileUploadConfig {    /**   单个数据大小 10M  */    private static final String SINGLE_FILE_SIZE = "10240KB";    /** 总上传数据大小 100M */    private static final String TOTAL_FILE_SIZE = "10240KB";
    @Bean    public MultipartConfigElement multipartConfigElement() throws IOException {        MultipartConfigFactory factory = new MultipartConfigFactory();        factory.setMaxFileSize(DataSize.parse(SINGLE_FILE_SIZE));        ///        factory.setMaxRequestSize(DataSize.parse(TOTAL_FILE_SIZE));        return factory.createMultipartConfig();    }}
123456789101112131415161718192021文件上传工具类import cn.hutool.core.date.DateUtil;import java.text.DecimalFormat;import java.util.Date;
/** * 文件上传相关工具类 * @author fangqi174956 */public class FileUploadUtils {
    /**     * 唯一ID生成器,可以生成唯一ID     * @return     */    public static String generateUniqueId() {        return DateUtil.format(new Date(),"yyyyMMdd") +System.currentTimeMillis();    }
    /**     * 文件名称替换工具,将文件名称替换为随机名称     * @param oldName     * @return     */    public static String generateFileName(String oldName){        String suffix = oldName.substring(oldName.lastIndexOf("."));        return generateUniqueId()+suffix;    }
    /**     * 将文件大小转换成 KB MB GB     * @param size     * @return     */    public static String getNetFileSizeDescription(long size) {        StringBuffer bytes = new StringBuffer();        DecimalFormat format = new DecimalFormat("###.0");        if (size >= 1024 * 1024 * 1024) {            double i = (size / (1024.0 * 1024.0 * 1024.0));            bytes.append(format.format(i)).append("GB");        }        else if (size >= 1024 * 1024) {            double i = (size / (1024.0 * 1024.0));            bytes.append(format.format(i)).append("MB");        }        else if (size >= 1024) {            double i = (size / (1024.0));            bytes.append(format.format(i)).append("KB");        }        else if (size < 1024) {            if (size <= 0) {                bytes.append("0B");            }            else {                bytes.append((int) size).append("B");            }        }        return bytes.toString();    }    }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960新建文件上传接口 /uploadcotroller层import com.qingge.springboot.common.Result;import com.qingge.springboot.service.IFileUploadService;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/** * 文件上传管理控制器 * @author fangqi174956 */@RestController@RequestMapping("/files")public class FileUploadController {
    @Resource    private IFileUploadService fileUploadService;
    @PostMapping("/upload")    public Result upload(@RequestParam("file") MultipartFile file){        try {            fileUploadService.uploadFile(file);        } catch (Exception e) {            return Result.error("-1",e.getMessage());        }        return Result.success();    }}
12345678910111213141516171819202122232425262728293031service层接口/** * 文件上传 * @author fangqi174956 */public interface IFileUploadService {
    /**     * 上传文件     * @param file     * @return     * @throws Exception     */    String uploadFile(MultipartFile file) throws Exception;}1234567891011121314service层实现import com.qingge.springboot.config.upload.FileUploadProperties;import com.qingge.springboot.entity.Files;import com.qingge.springboot.service.IFileService;import com.qingge.springboot.service.IFileUploadService;import com.qingge.springboot.utils.FileUploadUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;import java.io.IOException;
/** * @author fangqi174956 */@Servicepublic class FileUploadServiceImpl implements IFileUploadService {        @Autowired    private FileUploadProperties uploadProperties;    @Resource    private IFileService fileService;
    @Override    public String uploadFile(MultipartFile file) throws IOException {        if(!uploadProperties.getAllowTypes().contains(file.getContentType())){            throw new IOException("文件上传类型错误!");        }        String fileName = FileUploadUtils.generateFileName(file.getOriginalFilename());        file.transferTo(new File(uploadProperties.getPath()+fileName));
        // 将新上传到文件信息存储到数据库        Files newFile = new Files();        newFile.setName(file.getOriginalFilename());        String type = fileName.substring(fileName.indexOf(".")+1);        newFile.setType(type);        newFile.setSize(FileUploadUtils.getNetFileSizeDescription(file.getSize()));        newFile.setUrl("http://localhost:9090/files/" + fileName);        fileService.save(newFile);        return fileName;    }}
1234567891011121314151617181920212223242526272829303132333435363738394041424344前端页面使用常规html元素标签<input type="file" @change="getFile($event)"><input type="button" value="上传" @click="upload()">12发送请求实现上传
upload() {this.request.post("/files/upload",this.formData).then(res => {if (res.code == '200') {console.log('新到文件名',res.data)this.$message.success("文件上传成功")}});},getFile(event) {let file = event.target.files[0];let fileName = file.name;let index = fileName.lastIndexOf(".");let fileType = ['png','jpeg','jpg','jif','doc','pdf','xls']if (index != -1) {let suffix = fileName.substr(index + 1).toLowerCase();if (fileType.includes(suffix)) {this.formData.append("file",file);}else {this.$message.error("文件格式错误!请选择'png','jpeg','jpg','jif','doc','pdf','xls'格式的文件")}}},
12345678910111213141516171819202122使用ElementUI 的上传组件<el-upload action="http://localhost:9090/files/upload" :show-file-list="false"        :on-success="handleFileUploadSuccess"         style="display: inline-block"><el-button type="primary" class="ml-5">上传文件 <i class="el-icon-top"></i></el-button></el-upload>————————————————版权声明:本文为CSDN博主「Fq琦琦」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。原文链接:https://blog.csdn.net/weixin_40879055/article/details/124758828
posted @ 2022-08-31 13:54  红尘沙漏  阅读(1192)  评论(0编辑  收藏  举报