嗨,我已经搜索了从Android手机到服务器的图片上传,我已经完成了以下代码
例如
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < nameValuePairs.size(); index++) {
if (nameValuePairs.get(index).getName()
.equalsIgnoreCase("image")) {
entity.addPart(nameValuePairs.get(index).getName(),new FileBody(new File(
nameValuePairs.get(
index)
.getValue()),
"image/jpg"));
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost,
localContext);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
不知道为什么但是图片没有上传到服务器而我正在关注logcat
05-08 23:20:17.452: I/System.out(2501): Response from serveer <pre>Array
05-08 23:20:17.454: I/System.out(2501): (
05-08 23:20:17.455: I/System.out(2501): [image] => Array
05-08 23:20:17.455: I/System.out(2501): (
05-08 23:20:17.455: I/System.out(2501): [name] => IMG_20130101_164850.jpg
05-08 23:20:17.455: I/System.out(2501): [type] =>
05-08 23:20:17.455: I/System.out(2501): [tmp_name] => C:\Windows\Temp\php5CD4.tmp
05-08 23:20:17.456: I/System.out(2501): [error] => 0
05-08 23:20:17.456: I/System.out(2501): [size] => 1988151
05-08 23:20:17.456: I/System.out(2501): )
05-08 23:20:17.456: I/System.out(2501): )
此处来自服务器 TYPE没有返回值所以我无法提供更新
请有人帮忙解决这个问题
答案 0 :(得分:1)
我已经过测试,而且它已经完全正常工作了
您只需要更改
此代码
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE);
到
MultipartEntity entity = new MultipartEntity( 的 HttpMultipartMode.STRICT 强>);
并且所有其他代码都可以完成
答案 1 :(得分:0)
有两种方式可以想到:
坏(吃掉记忆)
MultipartEntity entity = new MultipartEntity();
FileBody fileBody = new FileBody(...)
entity.addPart("nameOfThePartTheServerExpects", fileBody);
entity.addPart(...) // additional parts if the server needs stuff.
httpPost.setEntity(entity);
httpClient.execute(httpPost, localContext);
好(更好记忆)
MultipartEntity entity = new MultipartEntity();
InputStreamBody inputStreamBody = new InputStreamBody(is, someRandomFilename);
entity.addPart("nameOfThePartTheServerExpects", inputStreamBody);
entity.addPart(...) // additional parts if the server needs stuff.
httpPost.setEntity(entity);
httpClient.execute(httpPost, localContext);
我强烈建议您从网页上检查帖子以获得正常的Web实现,这样您就可以看到所有部件的名称是什么,这些部件将对应于所有entity.addPart()。
此外,您不建议使用FileBody,请参阅API。