import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @NAME: hzan
* @DATE: 2022/10/28
**/
@Slf4j
public class FileUtil{
static String filePath="url";
/**
* 上传文件方法
*/
@RequestMapping(method = RequestMethod.POST, path = "/test")
@ResponseBody
public Map<String, String> test(HttpServletRequest request) {
Map<String, String> map = new HashMap<>();
map.put("code", "100");
try {
Part part = request.getPart("file_id");
String header = part.getHeader("content-disposition").replace("form-data; ", "");
String[] strs = header.split(";");
String str = "";
//文件后缀例如 .pdf .doc .jpg
str = strs[1].substring(strs[1].indexOf(".") + 1, strs[1].length() - 1);
//自行根据后缀或者流可以判断是文件类型自己研究
String uuid = "";
for (int i = 0; i < 10; i++) {
uuid = UUID.randomUUID().toString().replaceAll("-", "");
}
String folder = new SimpleDateFormat("yyyyMMdd").format(new Date());
String txtUrl = filePath + folder;
//文件上传服务器地址
File file1 = new File(txtUrl);
if (!file1.exists()) {
file1.mkdir();
}
part.write(filePath + folder + "/" + uuid + "." + str);
String pdf=txtUrl+ "/" + uuid + "." + str;
log.info("txtUrl====:{}",pdf);
map.put("code", "200");
map.put("url", "/" + folder + "/" + uuid + "." + str);
} catch (Exception e) {
e.printStackTrace();
return map;
}
return map;
}
}
可以根据上述代码将自己的文件上传服务器