好的,我正在尝试使用Java / Apache-HttpComponents将音频文件上传到服务器。服务器期望文件的MimeType为“audio / wav”。这是我正在尝试的:
File file = new File("testfile2.wav");
HttpPost httpPost = new HttpPost(uploadURL);
HttpResponse httpResponse;
String htmlResponse = "";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(file, ContentType.create("audio/wav"));
builder.addPart("mediaListForm.mediaForms[0].description", new StringBody("RBT Name", ContentType.TEXT_PLAIN));
builder.addPart("mediaListForm.mediaForms[0].artistId", new StringBody("2649", ContentType.TEXT_PLAIN));
builder.addPart("mediaListForm.mediaForms[0].categoryId", new StringBody("2", ContentType.TEXT_PLAIN));
builder.addPart("mediaListForm.mediaForms[0].file;", fileBody);
httpPost.setEntity(builder.build());
如果我没有指定MimeType,那么默认的MimeType将作为“application / octet-stream”发送,服务器拒绝我的请求。如果我指定mime类型如上new FileBody(file, ContentType.create("audio/wav"));
那么服务器说Invalid value for field mediaListForm.mediaForms[0].file
。我尝试调试并探索了这样的请求对象:
------WebKitFormBoundaryqQFxF4y3FTYY3pEf
Content-Disposition: form-data; name="mediaListForm.mediaForms[0].file";
Content-Type: audio/wav
我的请求中缺少文件名,有任何建议吗?
答案 0 :(得分:0)
不确定为什么以下方法无效:
builder.addPart("mediaListForm.mediaForms[0].file", fileBody);
//If filebody contains custom contentType it does not work otherwise file is uploaded but server rejects it because of invalid contentType
现在有多种方法可以向我们的实体添加文件,有些方法期望FileInputStream有些需要File,使用服务器期望的那个,就像我试过FileInputStream它服务器抛出异常而我想通了我不得不发送文件而不是,所以这种方法就像一个魅力。
builder.addBinaryBody("mediaListForm.mediaForms[0].file", file, ContentType.create("audio/wav"), rbt.getFullPath());