我試圖上傳一個文件和其他表單數據與澤西島使用multipart/form-data客戶端。我正在使用Jersey上傳到REST Web服務。這裏是服務器代碼:嘗試上傳文件到JAX-RS(澤西島)服務器
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String create(@FormDataParam("file") InputStream file,
@FormDataParam("file") FormDataContentDisposition fileInfo,
@FormDataParam("name") String name,
@FormDataParam("description") String description) {
Ingredient ingredient = new Ingredient();
ingredient.setName(name);
ingredient.setDescription(description);
ingredient.setImageName(fileInfo.getFileName());
ingredient.setImagePath(context.getRealPath("/resources/uploads/"));
// TODO save the file.
try {
JSONObject json = new JSONObject();
try {
ingredientService.create(ingredient);
} catch (final InvalidParameterException ex) {
logger.log(Level.INFO, ex.getMessage());
json.put("result", false);
json.put("error", ex.getMessage());
return json.toString();
} catch (final GoodDrinksException ex) {
logger.log(Level.WARNING, null, ex);
json.put("result", false);
json.put("error", ex.getMessage());
return json.toString();
}
json.put("ingredient", JsonUtil.ingredientToJSON(ingredient));
return json.put("result", true).toString();
} catch (JSONException ex) {
logger.log(Level.SEVERE, null, ex);
return "{\"result\",false}";
}
}
我已經測試了服務器代碼,在我的桌面上使用基本的html表單,它工作正常。問題似乎在客戶端。這裏是相關的客戶端代碼。
ClientConfig config = new DefaultClientConfig();
client = Client.create(config);
client.addFilter(new LoggingFilter());
webResource = client.resource("http://localhost:8080/webapp/resources").path("ingredient");
FormDataMultiPart fdmp = new FormDataMultiPart();
if (file != null) {
fdmp.bodyPart(new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
}
fdmp.bodyPart(new FormDataBodyPart("name", ingredient.getName()));
fdmp.bodyPart(new FormDataBodyPart("description", ingredient.getDescription()));
ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class, fdmp);
String string = response.getEntity(String.class);
logger.log(Level.INFO, "response: {0}", string);
我從服務器獲取400響應「客戶端發送的請求是語法不正確」
這裏是吐出記錄器的消息,這個人是沒有文件以保持輸出簡短:
1 > POST http://localhost:8080/webapp/resources/ingredient
1 > Content-Type: multipart/form-data
1 >
--Boundary_5_1545082086_1303666703655
Content-Type: text/plain
Content-Disposition: form-data;name="name"
Adam
--Boundary_5_1545082086_1303666703655
Content-Type: text/plain
Content-Disposition: form-data;name="description"
Test
--Boundary_5_1545082086_1303666703655--
我在做什麼錯誤的客戶端,以使其正常工作?
樣品:http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/ – 2012-08-22 19:54:25
哪個選項沒有你設置爲顯示請求正文,我啓用了'ServerProperties.TRACING = ALL'和'ServerProperties.TRACING_THRESHOLD = VERBOSE'。但它不顯示請求主體 – 2014-07-21 09:03:02