XMLHttpRequest发送请求

利用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);

}


posted @ 2017-04-08 10:44  SShoo  阅读(1860)  评论(0编辑  收藏  举报