【发布时间】:2017-09-05 09:08:29
【问题描述】:
我有 angular2 前端和 Dropwizard 后端。我正在尝试将图片从前端上传到后端。
我的html代码:
<input type="file" name="file" (change)="fileChange($event)">
我的组件:
fileChange(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('file', file);
this.siteDescriptionService.sendPhoto(formData).subscribe(value => {
console.log("value", value);
});
}
}
我的服务:
sendPhoto(data): Observable<any> {
return this.http.postPhoto('api/site/savePhoto', data, null).map(res => res);
}
我的 http 拦截器:
postPhoto(url: string, params?: any, options?: RequestOptionsArgs): Observable<any> {
this.beforeRequest();
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
let reqOptions = new RequestOptions({ headers: headers });
return super.post(this.getFullUrl(url), params, reqOptions)
.catch(this.onCatch)
.do((res: Response) => {
this.onSuccess(res);
}, (error: any) => {
this.onError(error);
})
.finally(() => {
this.onFinally();
});
}
正在使用这样的负载发送请求:
------WebKitFormBoundaryAz4AnN4lFPWKUvmH 内容处置:表单数据;名称=“文件”;文件名="logo.png" 内容类型:image/png
-----WebKitFormBoundaryAz4AnN4lFPWKUvmH--
在我的服务器上我有:
@POST
@Timed
@Path("savePhoto")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(InputStream uploadedInputStream) throws IOException {
String uploadedFileLocation = "/tmp/photo1.png";
FormDataMultiPart part = new FormDataMultiPart().field("file", uploadedInputStream, MediaType.TEXT_PLAIN_TYPE);
FormDataBodyPart p = part.getField("file");
InputStream i = (InputStream) p.getEntity();
writeToFile( i, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.ok(output).build();
}
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation)
throws IOException {
int read;
final int BUFFER_LENGTH = 1024;
final byte[] buffer = new byte[BUFFER_LENGTH];
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
out.flush();
out.close();
}
一切正常,正在保存文件,但它与整个请求负载一起保存,包括Content-Disposition、Content-Type 标头等,因此文件“损坏”。
如何从文件中删除 Content-Disposition 标头?
【问题讨论】:
标签: java angular multipartform-data dropwizard