URL: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();
}
}
}
请按照以下步骤操作:
添加 jersey-multipart 依赖项。
在您的应用程序类(或
web.xml
)中启用MultipartFeature.class
。请勿 在邮递员请求中添加 Content-Type 标头。
对我来说,上述步骤有效。请告诉我这是否对您有帮助。
我遇到了同样的问题,请确保您没有修改标题,尤其是内容类型和内容长度