一、示例代码
/**
* 功能: 文件上传工具类 示例代码
*
* @author CHY
*/
@Api("文件上传中心中心")
@RestController
public class FileController {
@Resource
private FileUtils fileUtils;
/**
* 上传文件
* @param multipartFile 文件
* @return
*/
@PutMapping("/uploadFile")
@ApiOperation(value = "上传文件", httpMethod = "PUT", notes = "上传文件")
public String uploadFile(@RequestParam("file") MultipartFile multipartFile) {
String fileUrl = fileUtils.saveFile(multipartFile);
return "上传成功,路径为"+fileUrl;
}
/**
* 删除文件
* @param fileUrl 一般为文件名称:head_A57AF2B824AF45FEA30E247607F9E06C.jpg
* @return
*/
@GetMapping("/deleteFile")
@ApiOperation(value = "删除文件", httpMethod = "GET", notes = "删除文件")
public String deleteFile(String fileUrl) {
int delFile = fileUtils.delFile(fileUrl);
if (delFile > 0 ){
return "删除成功";
}else {
return "删除失败";
}
}
}
二、操作步骤
1.访问Swagger2
http://127.0.0.1:8080/swagger-ui.html
2.上传文件
3.删除文件
三、文件上传工具类
/**
* 功能: 文件上传工具类
*
* @author CHY
*/
@Repository
@Slf4j
public class FileUtils {
@Value("${base.path.img-file}")
private String diskPath;
@Value("${base.path.img-file-url}")
private String imgFileUrl;
public String saveFile(MultipartFile multipartFile) {
String no = IdGeneratorUtil.UUID32Generate();
String name = multipartFile.getOriginalFilename();
String[] names = name.split("\\.");
String fileEnd = names[names.length - 1];
log.info("name:{},names:{}",names,names);
String pname = names[0]+"_"+no + "." + fileEnd;
//String fileName=name.substring(0,name.lastIndexOf("."));
//String fileType=name.substring(name.lastIndexOf("."));
//String pname = fileName+"_"+no + fileType;
String diskUrl = diskPath + File.separator + pname;
log.info("新增图片文件:" + diskUrl);
File diskDir = new File(diskPath + File.separator + pname);
if (!diskDir.getParentFile().exists()) {
diskDir.getParentFile().mkdirs();
}
try (InputStream is = multipartFile.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(diskUrl))) {
int num = 0;
while ((num = bis.read()) != -1) {
bos.write(num);
}
} catch (Exception e) {
log.error(e.getMessage());
throw new RuntimeException("文件上传错误,请联系管理员");
}
return imgFileUrl + pname;
}
/**
*
* @param fileUrl 请求地址
* @return int 删除结果 1 已删除 0 未删除
*/
public int delFile(String fileUrl) {
String[] routes = fileUrl.split("/");
String fileDesk = diskPath + File.separator + routes[routes.length - 1];
File file = new File(fileDesk);
if (file.exists()) {
file.delete();
return 1;
}
return 0;
}
}