我正在将图像从 Android 发送到 WCF 服务器。我尝试在多部分正文中发送 FileBOdy,但这并没有完成工作。最后,我尝试在多部分正文中发送 ByteArrayBody。它确实有效,但我在服务器中得到了损坏的图像。我搜索了很多,但无法为我的问题找到可接受的解决方案。有人能在我的 Android 或 WCF 代码中发现错误吗?
安卓代码
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
String URL1 = "http://rohit-pc:8078/service1.svc/UploadImage";
HttpPost httpPost = new HttpPost(URL1);
ContentBody bin = null;
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
reqEntity.addPart("image", bab);
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
WCF 代码
public string GetStream(Stream str,string filename) {
Guid guid = Guid.NewGuid();
string Path = System.Web.Hosting.HostingEnvironment.MapPath("~/Images");
FileStream file = new FileStream(Path + "/" +filename, FileMode.Create);
byte[] bytearray = new byte[100000000];
int bytesRead, totalBytesRead = 0;
do {
bytesRead = str.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
file.Write(bytearray, 0, bytearray.Length);
file.Close();
file.Dispose();
return "Success";
}