在我的 android 应用程序中,我通过 http post 将图像上传到服务器 (C#) 并成功上传到服务器。
听到的是图片上传的代码:
public static String uploadImagePost(String url, String imagePath) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
// add header
httpPost.addHeader("FileName", "android"+System.currentTimeMillis()+".jpg");
httpPost.setHeader("User-Agent", "android_client");
httpPost.addHeader("accept", "application/json");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
/* example for setting a HttpMultipartMode */
builder.setMode(HttpMultipartMode.RFC6532);
/* example for adding an image part */
builder.addPart("image/jpeg", new FileBody(new File (imagePath)));
httpPost.setEntity(builder.build());
HttpResponse response = httpClient.execute(httpPost, localContext);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
}
所以我的问题是我上传的图片不可读。 然后我使用编辑器检查了图像的来源,所以我注意到图像源中包含以下文本行。
标题:
--5VkWFM_KqrrWu4l-DOUIyJabHz5tZ5_jp
Content-Disposition: form-data; name="image/jpeg"; filename="tempimage.jpg"
Content-Type: application/octet-stream
页脚:
--5VkWFM_KqrrWu4l-DOUIyJabHz5tZ5_jp
删除上面的页眉和页脚并保存图像后,图像现在可读了。所以问题是页眉和页脚。我该如何解决这个问题?
最佳答案
图像解码
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitmapDrawable drawable = (BitmapDrawable) userPhoto.getDrawable();
yourSelectedImage= drawable.getBitmap();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG,100,baos);
imageData = baos.toByteArray();
使用Httppost发送图片
public static HttpResponse sendImage(byte[] image) {
HttpResponse responsePOST = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(postURL);
post.setHeader("Accept", "application/json");
ByteArrayBody bab = new ByteArrayBody(image, firstname+".png");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("user_profile[image_attributes[attachment]]", bab);
post.setEntity(reqEntity);
responsePOST = client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return responsePOST;
}
关于android - 将图像上传到android中的服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22404167/