利用FormData
對象,你能夠使用一系列的鍵值對來模擬一個完整的表單,而後使用XMLHttpRequest
發送這個"表單".前端
【前端demo】(angular2)後端
let xhr = new XMLHttpRequest(),
formData = new FormData();
this.onBeforeUpload.emit({
'xhr': xhr,
'formData': formData
});
for(let i = 0; i < this.files.length; i++) {
formData.append(this.name, this.files[i], this.files[i].name);
}
formData.append("bizTable",this.bizTable);
xhr.upload.addEventListener('progress', (e: ProgressEvent) => {
if(e.lengthComputable) {
this.progress = Math.round((e.loaded * 100) / e.total);
}
}, false);
xhr.onreadystatechange = (res) => {
if(xhr.readyState == 4) {
this.progress = 0;
if(xhr.status == 200){
this.onUpload.emit({xhr: xhr, files: this.files});
var result = JSON.parse(xhr.responseText);
this.filesDetail = this.filesDetail.concat(result.obj);
}else
this.onError.emit({xhr: xhr, files: this.files});
this.clear();
}
};
xhr.open('POST', this.url, true);
xhr.send(formData);
【後端接受請求】
public void upload(@RequestParam("flyFile") MultipartFile[] file,@RequestParam("bizTable")String bizTable){ int i = 0; List<Attachment> result = attachmentService.upload(file,bizTable); ResponseData responseData = new ResponseData(result); super.render(responseData);}