如何在Spring和Angular2中上传图片
我想在我的应用程序中上传图片这是我的Angular 2代码如何在Spring和Angular2中上传图片,spring,angular,file,upload,multipart,Spring,Angular,File,Upload,Multipart,我想在我的应用程序中上传图片这是我的Angular 2代码 constructor () { this.progress = Observable.create(observer => { this.progressObserver = observer }).share();
constructor () {
this.progress = Observable.create(observer => {
this.progressObserver = observer
}).share();
}
public makeFileRequest (url: string, params: string[], files: File[]):
Observable<any> {
return Observable.create(observer => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
构造函数(){
this.progress=Observable.create(observator=>{
this.progressObserver=观察者
}).share();
}
公共makeFileRequest(url:string,参数:string[],文件:File[]):
可观察{
返回可观察的。创建(观察者=>{
让formData:formData=new formData(),
xhr:XMLHttpRequest=新的XMLHttpRequest();
for(设i=0;i{
if(xhr.readyState==4){
如果(xhr.status==200){
next(JSON.parse(xhr.response));
observer.complete();
}否则{
观察者错误(xhr响应);
}
}
};
xhr.upload.onprogress=(事件)=>{
this.progress=Math.round(event.loaded/event.total*100);
this.progressObserver.next(this.progress);
};
xhr.open('POST',url,true);
xhr.send(formData);
});
}
这是我的弹簧控制器
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
@RequestParam("file") MultipartFile uploadfile) {
try {
// Get the filename and build the local file path (be sure that the
// application have write permissions on such directory)
String filename = uploadfile.getOriginalFilename();
String directory = "/assets/images";
String filepath = Paths.get(directory, filename).toString();
// 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);
}
@RequestMapping(value=“/upload”,method=RequestMethod.POST)
@应答器
公共响应上载文件(
@RequestParam(“文件”)多部分文件(上传文件){
试一试{
//获取文件名并生成本地文件路径(确保
//应用程序(对该目录具有写入权限)
字符串文件名=uploadfile.getOriginalFilename();
String directory=“/assets/images”;
String filepath=path.get(目录,文件名).toString();
//在本地保存文件
缓冲输出流=
新的BufferedOutputStream(新文件输出流(新文件路径));
stream.write(uploadfile.getBytes());
stream.close();
}
捕获(例外e){
System.out.println(e.getMessage());
返回新的响应属性(HttpStatus.BAD_请求);
}
返回新的响应状态(HttpStatus.OK);
}
我得到了这个错误
错误{“timestamp”:1498220487868,“status”:400,“ERROR:“Bad Request”,“exception:“org.springframework.web.multipart.support.MissingServletRequestPartException”,“message:“所需的请求部分“file”不存在”,“path:“/webapp/api/picture/upload”}您指定的
@RequestParam(“file”)
,这意味着Spring将使用键file
等待一个参数,但您将使用键uploads
附加数据
另外,正如所说,您正在接收一个多部分文件数组,而不仅仅是一个
如果要使用密钥文件
,请更正:
// Front-End: change "uploads" to "file"
formData.append("file[]", files[i], files[i].name);
如果要使用键上传
,请更正:
// Back-End: change "file" to "uploads" and takes a MultipartFile array
@RequestParam("uploads") MultipartFile[] uploadfile
另外,由于我可以看到上传了多个文件,所以您应该将参数更改为数组:
@RequestPart(“uploads”)MultipartFile[]uploads
@ledniv Ah您是正确的,我将更新答案。如何上传一个文件而不是多个文件?因为我犯了错误again@CrazyDeveloper删除MultipartFile
上的方括号和键uploads
,只在formData
上附加一个文件。但我得到了相同的错误,错误{“timestamp”:149829320921,“status”:400,“error”:“请求错误”,“异常”:“org.springframework.web.multipart.support.MissingServletRequestPartException”,“消息”:“所需的请求部分‘上载’不存在”,“路径”:“/webapp/api/picture/upload”}请查看:
// Back-End: change "file" to "uploads" and takes a MultipartFile array
@RequestParam("uploads") MultipartFile[] uploadfile