通过FormData对象可以组装一组用 XMLHttpRequest发送请求的键/值对;
同时可以实现文件的上传!
使用他的append方法就行;最值得注意的是在angualr2中千万别写请求格式!!
1、文件获取
<input id="saveFile" type="file" multiple="true" name="file" class="form-control"
(change)="fileChange($event,txDetailFm.controls['file'])" placeholder="上传文件" required>
2、angular2方法获取到文件 uploadFile 自己定义的变量File类型就行
fileChange( event: any, ele: FormControl ) {
this.uploadFile = event.target.files[0] ;}
3、单机上传的方法
saveFile() {
const formData = new FormData();
formData.append('file', this.uploadFile );
formData.append('test', 'test' );
console.log(formData.get('file'));
let myHeaders: Headers;
myHeaders = this.httpConstants.headers;
// 不要 myHeaders.append( 'Content-Type', 'multipart/form-data;' );
const req = new Request( {
method: RequestMethod.Post,
url: this.httpConstants.uploadFile,
headers: myHeaders,
body: formData
} );
this.httpUtil.send4Ob( req ).subscribe(( res: Response ) => {
} );
}
4、springmvc controller
@RequestMapping(value = "uploadFile", method = { RequestMethod.POST })
public void uploadFile(MultipartHttpServletRequest req, HttpServletResponse res,MultipartFile file, String test) {
logger.info(Thread.currentThread().getStackTrace()[1].getMethodName());
}