我正在尝试使用angular js + spring boot上传excel文件。文件上传成功,但文件似乎已损坏。我无法打开文件。这是我的代码。
的index.html
<p align="right">
<input type = "file" id="file" name="file"/>
<button ng-click="uploadFile()">Upload</button>
</p>
controller.js
function uploadFile() {
var file = document.getElementById('file').files[0];
console.log('file is ' );
console.log(file);
var uploadUrl = "/uploadAsExcel";
var fd = new FormData();
fd.append('uploadfile', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
Controller.java
@RequestMapping(value = "/uploadAsExcel", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(@RequestParam("uploadfile") MultipartFile uploadfile) {
try {
// Get the filename and build the local file path
String filename = uploadfile.getOriginalFilename();
String contentType = uploadfile.getContentType();
System.out.println("ContentType: "+contentType);
String filepath = "C:\\Users\\user122\\Documents\\MyFiles\\"+filename;
//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);
}
WebConfig.java
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
//resolver.setDefaultEncoding("utf-8");
resolver.setMaxUploadSize(-1);
return resolver;
}
Excel文件上传成功,但是当我打开文件时,它会显示“文件已损坏”。基本上,我需要使用Excel API读取excel文件并执行一些操作。
你能帮助别人吗?
谢谢, KARTHIK