网址:http://localhost:8080/RESTfulExample/rest/file/upload 方法:发布
回应:
相同的代码正在使用html表单,但是在邮递员中它会抛出400个BAD REQUEST,我在google上查找解决方案并发现边界丢失,如何解决?因为我必须通过Jquery和rest客户端从移动应用程序和Web客户端等多个客户端接收文件。
@Path("/file")
public class UploadFileService {
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
try {
String uploadedFileLocation = "/home/nash/" + fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
System.out.println("File uploaded..........");
return Response.status(200).entity(output).build();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception " + e);
return null;
}
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:10)
请按以下步骤操作:
添加jersey-multipart依赖项。
在您的应用程序类中(或在web.xml
中)启用MultipartFeature.class
。
不要在邮递员请求中添加Content-Type标头。
对我来说,上述步骤有效。如果这对你有帮助,请告诉我。