我正试图用以下代码将文件发送到服务器
private static HttpEntity getHttpEntity(File[] files, List<BasicNameValuePair>
otherParams, String fileName) {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setCharset(Charset.forName("UTF-8"));
entity.setBoundary(BOUNDARY);
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
if (otherParams != null) {
for (NameValuePair pair : otherParams) {
entity.addTextBody(pair.getName(),pair.getValue(),contentType);
}
}
if (files != null) {
for(int i=0;i<files.length;++i) {
try {
FileInputStream inputStream = new FileInputStream(files[i]); entity.addBinaryBody("file"+i,inputStream,ContentType.create(HTTP.OCTET_STREAM_TYPE), fileName);
LogUtils.d("added file:"+files[i].getAbsolutePath());// fileBody);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
LogUtils.d("failed to add file");
}
}
}
return entity.build();
}
服务器显示以下到达文件的日志
2015-03-05 10:17:06,214 [4] DEBUG Controllers.ApiControllerBase - {[CallingFunction, UploadEventFile], [CallingFile, c:DropboxsrcControllersValuesController.cs], [CallingLine, 1804], [CurrentUser, 123456789], [Message, got headers: [{"Key":"Content-Type","Value":["multipart/form-data; boundary=com.lenabru.apps; charset=UTF-8"]}]]}
2015-03-05 10:17:06,214 [4] DEBUG Controllers.ApiControllerBase - {[CallingFunction, UploadEventFile], [CallingFile, c:DropboxsrcControllersValuesController.cs], [CallingLine, 1805], [CurrentUser, 1234567890], [Message, got content: --com.lenabru.apps
Content-Disposition: form-data; name="file0"; filename="lenkovi-jibrish"
Content-Type: application/octet-stream
?PNG
IHDR ? , ??C? sBIT ??O? IDATx?d??%G?%v????%???L ??*??P ???)#B? ? ?'? ??2?A??= !e??fMuwa) ? $ ?glws7S???? $b????.G? ?? ?????*hf X P?(4??b @ `$?? I jB?? 1???F??? ?@R
#? R?P 0 ! ?TU ` ???#if?? ? 5R VS ?! (0 ???f U w? RX ??P3 ?A
?? h L? ?fBRM?i"
H03 T @C5Pa$D? ?F??`BT?? ?* ?? J? ?L ( BAZ I1 `?* j4?R5??? & ?)i K?@S?__2V ?"0S?r
??? -??L@S????????? ??? }?A ? ??? 3{yq???? ???X?????L?;?????w?g/?? ???nG?V??I? ?
Truncated for the sake of the question
--com.lenabru.apps--
]}
该文件似乎是在服务器上收到的,但下面的代码显示有0个文件附加到请求
if (HttpContext.Current.Request.Files.Count < 1)
{
var error = Errors.NoFilesAttached;
Log(error.Description);
return Request.CreateResponse(error);
}
我正在使用以下库发送请求通过gradle 下载库
compile 'org.apache.james:apache-mime4j:0.7.2'
compile('org.apache.httpcomponents:httpmime:4.3.6')
compile 'org.apache.httpcomponents:httpcore:4.3.+'
问题:如果在服务器上接收到二进制部分,HttpContext.Current.Request.Files.Count行总是返回0
这是罪魁祸首entity.setCharset(Charset.forName("UTF-8"));
删除这一行修复了的问题