一.文件上传配置
spring:
servlet:
###多文件上传配置
multipart:
file-size-threshold: 100MB
max-file-size: 10MB
max-request-size: 100MB
或者
###文件上传配置
# 单个上传文件大小限制(默认1MB)
spring.servlet.multipart.max-file-size=10MB
# 总上传文件大小限制(默认10MB)
spring.servlet.multipart.max-request-size=50MB
#文件上传路径
#/root/docker/
#my.upload.imgPath=D://file/upload/
#文件上传绝对路径(注意:结尾“/”)
my.upload.imgPath=/root/docker/upload/
#文件上传根目录
dirPath=upload
#rootPath=D://file
#文件上传根目录的上级绝对路径
rootPath=/root/docker
二.静态路径映射绝对路径(重点)
原由:
文件上传是在web开发中所遇到的比较常见的需求了,常见的文件上传有几种
- 一是将文件上传到oss等类似的文件服务器上,然后在数据库中保存相应的文件地址,上传有对应的sdk,地址直接就是一个http地址,这种方式下的文件上传及显示比较简单,但是成本较大。
- 另一种就是将文件上传到项目路径的静态资源文件夹resources/下,这种方式比较方便,也比较省成本。在Springboot还未流行的时候,我们一般是用tomcat来运行一个web项目,这时候将文件上传到资源文件夹下没什么问题。但是**springboot推荐使用jar包的方式来运行(如果是在idea中直接运行,非jar包,则没有半点问题),这时候再将文件上传到resources文件夹下就会有问题,会提示文件路径不存在。因为resource的文件操作是依赖于文件系统的,将项目打成一个独立jar包后是没有resource这个文件夹的,解压jar包就知道了。**那么这时候我想要上传文件到服务器上怎么办呢,Springboot提供了一个静态资源的映射方式,你可以添加一个外部文件夹并将其作为一个静态资源文件夹的映射,也就是说添加这个映射后你可以在项目中像访问静态资源文件夹一样来访问外部的文件夹。具体怎么做呢,添加一个类就够了
@Configuration
public class FileUploadConfig implements WebMvcConfigurer {
@Value("${my.upload.imgPath}")
private String path;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String staticMapping = "/upload/**";
String localDirectory = "file:" + path;
registry.addResourceHandler(staticMapping).addResourceLocations(localDirectory);
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
三.文件上传工具类
package com.zsc.shixun.utils;
import com.zsc.shixun.common.ResultCode;
import com.zsc.shixun.exception.ApiException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
/**
* <p>
* 文件工具类
* </p>
*
* @author ZWYZY
* @since 2020/6/15
*/
@Service
public class FIleUtils {
@Value("${dirPath}")
private String directoryPath;
@Value("${rootPath}")
private String rootPath;
/**
* 单文件上传
*
* @param dirPath
* @param fileName
* @param fileUpload
*/
public String upload(String dirPath, String fileName, MultipartFile fileUpload) {
File filePath = new File(dirPath);
if (!filePath.exists()) {
filePath.mkdirs();
}
try {
fileUpload.transferTo(new File(filePath, fileName));
System.out.println("文件上传成功,路径为:" + filePath + "\\" + fileName);
return "/" + directoryPath + "/" + fileName;
} catch (Exception e) {
System.out.println("文件上传失败");
throw new ApiException(ResultCode.FILE_UPLOAD_ERROR);
}
}
/**
* 删除单个文件
*
* @param fileName 要删除的文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public boolean deleteFile(String fileName) {
File file = new File(rootPath + fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("删除单个文件" + fileName + "成功!");
return true;
} else {
System.out.println("删除单个文件" + fileName + "失败!");
return false;
}
} else {
System.out.println("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}
}
四,文件上传测试类demo
@PostMapping("/uploadFile")
@ResponseBody
public CommonResult uploadFile(MultipartFile fileUpload,@NotNull(message = "id不能为空") @RequestParam(required = false) Long id) {
String dirPath=null;
String fileName = fileUpload.getOriginalFilename();
fileName = UUID.randomUUID() + "_" + fileName;
System.out.println(path);
String fullPath = fIleUtils.upload(path, fileName, fileUpload);
userService.updateByImg(id, fullPath);
return ResultUtil.success("文件上传成功,亲!");
}
五.前端异步发送文件
//使用Ajax上传文件
function uploadFile() {
var formData = new FormData();//声明表单对象
//获取文件对象
formData.append("file", $('#fileToUpload').get(0).files[0]);
$.ajax({
url: '/ticket/uploadFile', /*接口域名地址*/
type: 'post',
data: formData,
async: true,
processData: false, // 不处理发送的数据
contentType: false, // 不设置Content-Type请求头
beforeSend: function () { //实现动画加载
$("#loading").html("<img src='/site/images/loading.gif' />");
},
success: function (res) { //上传成功
$("#loading").empty();
console.log(res);
if (res["msg"] == "success") {
// $('#fileInfo').empty();
console.log(res["link"]);
$('#fileInfo').html(
"文件上传成功!文件名:" + res['filename'] +
" <a οnclick=delFile('" + encodeURI(res['link']) + "') href='#'>删除</a> " +
" <a οnclick=viewFile('" + encodeURI(res['link']) + "') href='#'>查看</a> "
).removeClass();
$('#btnUpload').attr('disabled', false);
}
},
error: function () { //上传失败
$("#loading").empty();
}
})
}