我一直在使用这款在服务器上传图片的Android应用。我能够使用PHP成功上传,但我在.net webservice上上传时遇到了麻烦。负责网络服务的人给了我这些代码,所以我可以查看它。
在这里。
public Stream FileUpload(string fileName, Stream fileStream)
{
var serverPath = System.Web.Hosting.HostingEnvironment.MapPath("~/FileUpload/");
if (File.Exists(serverPath + fileName)) File.Delete(serverPath + fileName); // delete file if already used
//FileStream fileToupload = new FileStream("D:\\FileUpload\\" + fileName, FileMode.Create);
FileStream fileToupload = new FileStream(serverPath + fileName, FileMode.Create);
byte[] bytearray = new byte[10000];//
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
fileToupload.Write(bytearray, 0, bytearray.Length);
fileToupload.Close();
fileToupload.Dispose();
FileStream fs = File.OpenRead(serverPath + fileName);
WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return fs;
}
问题是我没有.net的经验,所以我不知道如何处理这种情况。从上面的参数可以看出,webservice中的上传图像功能似乎使用了一个fileStream。
修改
这是我的java代码。
HttpResponse httpResponse = null;
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(filePath));
byte[] data;
try {
data = IOUtils.toByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://localhost/fileUpload");
InputStreamBody inputStreamBody = new InputStreamBody(
new ByteArrayInputStream(data), fileName);
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder
.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file", inputStreamBody);
HttpEntity entity = multipartEntity.build();
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
if (httpResponse != null) {
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}