【发布时间】:2017-01-18 06:18:36
【问题描述】:
我正在尝试使用此代码上传图片:
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;
}
我有一个上传图片的网络服务,它有 5 个参数,其中 4 个是字符串,一个是字节数组 (byte[] f)
主要问题:如何将我的源文件(图像)转换为字节数组,以将图像上传到服务器上,上面的代码对应于这个网络服务。
【问题讨论】:
-
您的代码已经将文件作为字节数组上传。正常的分段上传就是这样做的。
标签: android arrays android-asynctask http-post android-image