我有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 内容处理:表格数据;命名=&#34;文件&#34 ;;文件名=&#34; logo.png&#34; 内容类型: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
标题等,因此文件变为&#34 ;碎&#34;
如何从文件中删除Content-Disposition标头?
答案 0 :(得分:0)
当您使用InputStream
参数时,您说您想要整个请求正文。如果您只想要一个零件,则需要使用@FormDataParam
和零件名称对其进行注释
public Response uploadFile(@FormDataParam("file") InputStream file,
@FormDataParam("file") FormDataContentDisposition fdcd) {
String filename = fcdc.getFileName();
// You don't need to create the FormDataMultiPart
// just save the InputStream parameter
}
为了使其正常工作,您还需要注册MutliPartFeature
env.jersey().register(MultiPartFeature.class);