发送和获取文件并将其保存到文件夹的正确方法是什么?
我发邮件来自邮递员的身体形式数据:2个键' uploadfile'每个都有一个拉链。
此代码只有一个zip并保存,忽略第二个zip。
如何实现它来保存这两个文件? 也。我应该在一个密钥中发送2个文件吗?或每个文件分开的键?
@RequestMapping(value = "/api/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
@RequestParam("uploadfile") MultipartFile uploadfile) {
try {
// Get the filename and build the local file path (be sure that the
// application have write permissions on such directory)
String filename = uploadfile.getOriginalFilename();
String directory = "C://Develop//files";
String filepath = Paths.get(directory, filename).toString();
filenameZip = "c:/Develop/files/"+filename;
directoryZip = "c:/Develop/files";
// Save the file locally
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filepath)));
stream.write(uploadfile.getBytes());
stream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// unzip(filenameZip, directoryZip);
return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile
邮差记录:
var data = new FormData();
data.append("uploadfile", "pasta1.zip");
data.append("uploadfile", "pasta2.zip");
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://localhost:8080/api/uploadFile");
xhr.setRequestHeader("authorization", "Basic b3BlcmF0aW9uczpvcGVyYXRpb25z");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "e7b6fcae-4a49-de34-ba7c-efd412fb244a");
xhr.send(data);
答案 0 :(得分:3)
你可以让你的服务接受多部分文件的数组,然后你可以发送到你想要的文件上传它,这是一个例子
@RequestMapping(value="/multipleSave", method=RequestMethod.POST )
public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files){
String fileName = null;
String msg = "";
if (files != null && files.length >0) {
for(int i =0 ;i< files.length; i++){
try {
fileName = files[i].getOriginalFilename();
byte[] bytes = files[i].getBytes();
BufferedOutputStream buffStream =
new BufferedOutputStream(new FileOutputStream(new File("F:/cp/" + fileName)));
buffStream.write(bytes);
buffStream.close();
msg += "You have successfully uploaded " + fileName +"<br/>";
} catch (Exception e) {
return "You failed to upload " + fileName + ": " + e.getMessage() +"<br/>";
}
}
return msg;
} else {
return "Unable to upload. File is empty.";
}
}
}
对于关键部分,您可以使用相同的密钥发送所有文件