临时保存文件 java
@RequestMapping("/uploadFile")
@ResponseBody
public void uploadFile(){
Map<String, Object> result = new HashMap<>();
var req = readJson();
String filePath = recruitmentService.uploadFile(req);
result.put("filePath",filePath);
writeJson(result);
}
@Override
public String uploadFile(Map fileMap) {
var uploadType = false;
var file = fileMap.get("data").toString();
if (file.startsWith("data:")) {
file = file.substring(file.indexOf(',') + 1);
}
file = StringUtils.replaceEach(file, new String[]{"\n", "\r"}, new String[]{"", ""}).trim();
byte[] bytes = Base64.getDecoder().decode(file);
var filePath = fileToBytes(bytes, "文件路径", fileMap.get("uploadName").toString());
return filePath;
}
public String fileToBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
file = new File(filePath + fileName);
if (!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file.getPath();
}
}