目录
前言
上传文件功能是每个项目必备的功能,通过多个项目不断升级而来,在实现相同效果的情况下,代码越来越简化。
代码中用到了hutool工具库,这个库确实比较强大,可以轻松解决很多问题。hutool官网api文档https://apidoc.gitee.com/dromara/hutool/
hutool官网https://hutool.cn/docs/#/
在拿到项目需求时,先以最快的速度完成需求,然后逐渐完善代码,完善的代码将用于下一个项目。
所有的项目,我们都遵守拿来即用原则。
功能介绍
单文件上传,多文件上传,wangedit富文本上传(大同小异,只是返回格式不同)
fileRootPath:是文件放置的父级路径,比如:lunbotu(轮播图),user/headimg(用户头像),user/photo(用户相册),videos(视频),等等,支持多级路径。
实现
依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.1</version>
</dependency>
配置
server:
servlet:
context-path: /tmpl
#上传文件配置
upload:
# 保存文件路径
path: D:/yanwei/projects/yanwei/files
# 访问url路径,/tmpl为前缀
webbasepath: http://127.0.0.1:8080/tmpl/file
package com.yanwei.tmpl.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Author 闫伟
* @DATE 2021/9/20 17:23
* @Description:
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Value("${upload.path}")
private String uploadPath = "";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/file/**").addResourceLocations("file:" + uploadPath + "\\");
}
}
Controller
package com.yanwei.tmpl.module.common.file;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.yanwei.tmpl.module.common.jpa.utils.Result;
import com.yanwei.tmpl.module.common.jpa.utils.ResultUtil;
import com.yanwei.tmpl.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Value;
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.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* 文件
*/
@RestController
@RequestMapping("/api/com/file")
public class FileUpController {
@Value("${upload.path}")
private String uploadPath;
@Value("${upload.webbasepath}")
private String webbasepath;
/**
* 单个文件
*
* @param file
* @return
*/
@PostMapping(value = "/up")
public Result up(@RequestParam("file") MultipartFile file, String fileRootPath) throws IOException {
if(!file.isEmpty()){
return ResultUtil.data(saveFile(file,fileRootPath));
}
return ResultUtil.data(getResult("","",""));
}
/**
* 多文件
*
* @param files
* @return
*/
@PostMapping(value = "/ups")
public Result ups(@RequestParam("files") MultipartFile[] files, String fileRootPath) throws IOException {
if(files.length > 0){
List<Map<String,String>> list = ListUtil.toList();
for (MultipartFile multipartFile : files) {
list.add(saveFile(multipartFile,fileRootPath));
}
return ResultUtil.data(list);
}
return ResultUtil.data(getResult("","",""));
}
/**
* WangEdit富文本编辑器文件上传
*
* {
* "errno": 0, // 注意:值是数字,不能是字符串.0:成功;1:失败
* "data": {
* "url": "xxx", // 图片 src ,必须
* "alt": "yyy", // 图片描述文字,非必须
* "href": "zzz" // 图片的链接,非必须
* },
* "message": "失败信息"
* }
* @param file
* @return
*/
@PostMapping(value = "/upWidthWangEdit")
public Object upWidthWangEdit(@RequestParam("file") MultipartFile file, String fileRootPath, HttpServletRequest httpServletRequest) throws IOException {
Map map = MapUtil.newHashMap();
if(!file.isEmpty()){
Map<String,String> saveFileResult = saveFile(file,fileRootPath);
map.put("errno",0);
map.put("data",saveFileResult);
}else{
map.put("errno",1);
map.put("message","上传失败,请重新上传");
}
return map;
}
/**
* 保存文件到本地
* @param multipartFile
* @param fileRootPath
* @return
* @throws IOException
*/
private Map<String,String> saveFile(MultipartFile multipartFile, String fileRootPath) throws IOException {
String fileName = multipartFile.getOriginalFilename();
//新文件名
String newFileName = String.format("%s.%s", IdUtil.simpleUUID(), FileUtil.getSuffix(fileName));
//相对路径和绝对路径
String newRelativePath = String.format("%s/%s", fileRootPath, newFileName);
String realPath = String.format("%s/%s", uploadPath, newRelativePath);
//创建文件夹
cn.hutool.core.io.FileUtil.mkParentDirs(realPath);
//保存文件到本地
multipartFile.transferTo(new File(realPath));
return getResult(newFileName,newRelativePath,String.format("%s/%s", webbasepath, newRelativePath));
}
/**
* 上传文件结果
* @param name
* @param path
* @param url
* @return
*/
private Map<String,String> getResult(String name,String path,String url){
Map<String,String> result = MapUtil.newHashMap();
result.put("name",name);//文件名
result.put("path",path);//相对路径
result.put("url",url);//绝对路径
return result;
}
}
效果-单文件