1
我想发送使用多部分实体 的图像数组,如想发送多个图像。签名 说法是在以下在Android中使用多部分实体发送图像阵列
entity.addPart("files[]", .....);
我怎样才能做到这一点?
我想发送使用多部分实体 的图像数组,如想发送多个图像。签名 说法是在以下在Android中使用多部分实体发送图像阵列
entity.addPart("files[]", .....);
我怎样才能做到这一点?
您可以使用HTTP mime库(首选4.3.3)和HTTP POST将文件上传到服务器。 PHP服务器将识别图像为您的案例中所需的FILE。 我创建了一个类,它可以帮助我的图像或文件上传到我的服务器
public class FileUploadHelper extends AsyncTask<Void, Void, Void> {
private MultipartEntityBuilder multipartEntity;
private String URL;
public FileUploadHelper(String URL) {
multipartEntity = MultipartEntityBuilder.create();
this.URL = URL;
}
@SuppressLint("TrulyRandom")
@Override
protected Void doInBackground(Void... arg0) {
try {
multipartEntity.addTextBody("<YOUR STRING KEY>", "<STRING VALUE>");
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
HttpClient httpclient;
httpclient = new DefaultHttpClient();
httpclient.getConnectionManager().closeExpiredConnections();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(multipartEntity.build());
HttpResponse response = httpclient.execute(httppost);
int responseCode = response.getStatusLine().getStatusCode();
String serverResponse = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void addFile(String key, File newFile) throws FileNotFoundException {
if (newFile.exists()) {
multipartEntity.addBinaryBody(key, newFile);
} else {
throw new FileNotFoundException("No file was found at the path " + newFile.getPath());
}
}
}
要使用这个类来创建FileUploader类的对象,然后调用其addFile()函数调用execute(),因为这类扩展了AsyncTask。在你的代码中,你已经有了File对象
File file = new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis())
+ ".jpg");
只需将此对象传递给addFile()即可。 addFile()的关键是你需要的“files []”。 请注意,您可能无法一次发送文件数组,因为密钥文件[]将被下一个文件覆盖,所以只有最后一张图片才会上传,所以最好多次发送请求关键“文件[]”取决于你要发送多少个文件
希望这会帮助你