您好我正在尝试在选中时立即上传文件。我收到了一个错误的请求400。 无法加载资源:服务器响应状态为400(错误请求) 我的代码如下。
<input type="file" (change)="fileChange($event)" placeholder="Upload file" >
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data;boundary=gc0p4Jq0M2Yt08jU534c0p');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
alert(ConnectionHelper.SERVER_URL
+ConnectionHelper.MEDIACHANNEL+ConnectionHelper.UPLOADFILE)
this._http.post(ConnectionHelper.SERVER_URL
+ConnectionHelper.MEDIACHANNEL+ConnectionHelper.UPLOADFILE, formData,options)
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
Spring控制器
@RequestMapping(value = "/api/mediaChannel/logoUpload", method = RequestMethod.POST)
@ResponseBody
public String logoUpload(@RequestParam("fileUpload") MultipartFile file,HttpServletResponse res, MultipartHttpServletRequest req) {
WebUtil wu = new WebUtil(res, req);
wu.allowCrossSiteMessages();
if (file.isEmpty()) {
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get("images\\" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "successfull";
}
答案 0 :(得分:0)
您好,您无法使用http帖子上传文件,而不需要使用xhr请求
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
return new Promise((resolve, reject) => {
let formData: any = new FormData();
let xhr = new XMLHttpRequest();
formData.append('uploadFile', file, file.name);
xhr.open('POST', url, true);
xhr.setRequestHeader('Authorization', 'JWT ' + localStorage.getItem('id_token'));//If you need pass authentication token
xhr.send(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
resolve(JSON.parse(xhr.responseText));
}
}
});
}
}