SpringBoot + vue 实现文件上传

概述文件上传使用场景

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

    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>
  1. 文件上传相关配置
    在项目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
  1. 创建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();
    }
}
  1. 文件上传工具类
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();
    }
    
}
  1. 新建文件上传接口 /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>

版权声明:本文为weixin_40879055原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。