我正在尝试使用以下代码上传图片:
private String uploadFile() {
String responseString = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL_M);
Log.i("UploadApp", "upload url: " + Config.FILE_UPLOAD_URL_M);
AndroidMultiPartEntity entity;
entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
// publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile;
sourceFile = new File(compressImage(filePath));
Log.i("UploadApp", "file path: " + filePath);
// Adding file data to http body
entity.addPart("f", new FileBody(sourceFile)); //problem is here
entity.addPart("category", new StringBody("Bill"));
entity.addPart("description", new StringBody("test single"));
entity.addPart("file", new StringBody("unknown1"));
entity.addPart("clientid", new StringBody("4"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: " + statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
Log.e("UploadApp", "exception: " + responseString);
} catch (IOException e) {
responseString = e.toString();
Log.e("UploadApp", "exception: " + responseString);
}
return responseString;
}
我有一个用于上传图像的Web服务,其中包含5个参数,其中4个是字符串,但一个是字节数组(byte [] f)
主要问题:如何将我的源文件(图像)转换为字节数组,以上述网络服务所对应的上述代码将图像上传到服务器上。
最佳答案
您可以使用android第三方“ AndroidAsync”。您可以通过此代码执行任何操作。
https://github.com/koush/AndroidAsync
谢谢