我正在尝试下载csv文件,并希望在执行我的应用程序时使用Spring MVC和Ajax Post请求将相同的csv文件上传到我的服务器位置路径。
从下面的代码中,我可以在运行我的应用程序时下载我的csv文件,但它没有同时上传到我的服务器位置路径或同时执行应用程序,我不知道为什么它是不上传。请帮我按照给定的路径上传文件。谢谢!
JS:
function download_csv(csv, filename) {
//filename = test.csv
//csv = "testname,testid
hello,10"
var csvFile;
var downloadLink;
// CSV FILE
csvFile = new Blob([csv], {type: "text/csv"}); //[object Blob]
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
var formData = new FormData(csvFile);
console.log(formData);//FormData {}
$.ajax({
url: "/uploadFile",
type: "POST",
//data: filename,
// data: new FormData(csvFile),
data: formData,
// enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
success: function (data) {
// Handle upload success
$("#upload-file-message").text("File succesfully uploaded");
},
error: function (errordata) {
console.log("error: "+errordata);//[object Object]
console.log("error data: "+JSON.stringify(errordata));
}
});//$.ajax()
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Make sure that the link is not displayed
downloadLink.style.display = "none";
// Add the link to your DOM
document.body.appendChild(downloadLink);
// Lanzamos
downloadLink.click();
}
控制器:
@Controller
public class MainController {
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
@RequestParam("filename") MultipartFile uploadfile) {
try {
// Get the filename and build the local file path
String filename = uploadfile.getOriginalFilename();
String directory = env.getProperty("paths.uploadedFiles");
String filepath = Paths.get(directory, filename).toString();
// 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);
}
return new ResponseEntity<>(HttpStatus.OK);
}
}
application.resources:
paths.uploadedFiles = /resources/test/
POST http://localhost:8000/uploadFile 400(错误请求)
错误数据:{"readyState":4,"responseText":"{\"timestamp\":1511523835282,\"status\":400,\"error\":\"Bad Request\",\"exception\":\"org.springframework.web.bind.MissingServletRequestParameterException\",\"message\":\"Required MultipartFile parameter 'filename' is not present\",\"path\":\"/uploadFile\"}","responseJSON":{"timestamp":1511523835282,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required MultipartFile parameter 'filename' is not present","path":"/uploadFile"},"status":400,"statusText":"Bad Request"}