我一直坚持这个问题。所以我使用SendGrid发送电子邮件,除了附加图像文件外一切正常,所以我按照this
的文档进行操作这是我的代码
private class SendDataInBackGround extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... arg0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.MAIL_URL);
try {
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("api_user", new StringBody(Constants.MAIL_USERNAME));
multipartEntity.addPart("api_key", new StringBody(Constants.MAIL_PASSWORD));
multipartEntity.addPart("to", new StringBody("me@mycompany.com"));
multipartEntity.addPart("subject", new StringBody("subject"));
multipartEntity.addPart("text", new StringBody("message"));
multipartEntity.addPart("from", new StringBody("someone@somewhere.com"));
File file = new File(Environment.getExternalStorageDirectory()
+ "/safe.png");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
multipartEntity.addPart("files", new FileBody(file));
httppost.setEntity(multipartEntity);
String res = httpclient.execute(httppost, new UploadResponseHandler());
return res;
} catch (ClientProtocolException e) {
return null;
} catch (IOException e) {
return null;
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Helper.createToast(getSherlockActivity(), result).show();
}
private class UploadResponseHandler implements ResponseHandler<String> {
@Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity();
String responseString = EntityUtils.toString(r_entity);
return responseString;
}
}
}
我不确定我错过了什么,或者有更好的解决方案来处理这个问题。
感谢。
答案 0 :(得分:1)
这是我正在使用的代码并且正在为我工作:
public void testUpload(String path,String url) {
HttpResponse response;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(url);
File f = new File(path);
FileBody b = new FileBody(f);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("ImageFile", b).build();
reqEntity.getContentType().toString();
httppost.setEntity(reqEntity);
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: "
+ resEntity.getContentLength());
}
Log.d("response", EntityUtils.toString(resEntity));
} catch (Exception e) {
// httpclient.close();
e.printStackTrace();
}
}
它基本相同我使用此方法将多个文件发送到我的服务器。希望它对你有所帮助,因为你和我的方法相似,所以不需要任何解释,但可以随意提问。