使用spring initializr初始化一个springboot项目

先编写yml配置文件,设置文件上传路径
server:
ip: localhost
port: 8000
files:
upload:
path: E:/file/h/uplods/
编写Controller
package com.song.boot.file;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
@RestController
public class FileController {
@Value("${files.upload.path}")
private String filesUploadPath;
@PostMapping("/file")
public String filesUpload(@RequestParam MultipartFile file) throws IOException, JSONException {
JSONObject result = new JSONObject();
if (file.isEmpty()) {
result.put("error", "空文件");
return result.toString();
}
String fileName = file.getOriginalFilename();
String prefix = fileName.substring(0, fileName.lastIndexOf("."));
String suffix = fileName.substring(fileName.lastIndexOf("."));
String filePath = filesUploadPath + fileName;
File fileTemObj = new File(filePath);
if (!fileTemObj.getParentFile().exists()) {
fileTemObj.getParentFile().mkdirs();
}
if (fileTemObj.exists()) {
int count = 1;
File file1 ;
while (true) {
file1 = new File(filesUploadPath + prefix + "-" + count + suffix);
if (file1.exists()) {
count++;
} else {
break;
}
}
fileTemObj = file1;
}
file.transferTo(fileTemObj);
return "success,filePath:" + fileTemObj.getAbsolutePath();
}
@GetMapping("/file/list")
public String queryFile() {
File file = new File(filesUploadPath);
return Arrays.toString(file.list());
}
@GetMapping("/file/{filename}")
public String fileDownload(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException, JSONException {
JSONObject result = new JSONObject();
File file = new File(filesUploadPath + "/" + filename);
if (!file.exists()) {
result.put("error", "文件不存在!");
return result.toString();
}
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setContentType("application/octet-stream");
ServletOutputStream outputStream = response.getOutputStream();
byte[] bytes = FileCopyUtils.copyToByteArray(file);
outputStream.write(bytes);
return "success";
}
@DeleteMapping("/file")
public String deleteFile(@RequestParam("filename") String filename) {
File file = new File(filesUploadPath + "/" + filename);
if (!file.exists()) {
return "文件不存在!";
} else {
if (file.delete()) {
return "文件已删除";
}
return "删除失败";
}
}
@GetMapping("/test/{name}")
public String names(@PathVariable("name") String name) {
return name;
}
}