我需要将手机中的所有图像上传到服务器,但问题是我使用Async来记忆内存。
我看到很多解决方案,他们要求用户缩小图像,但我需要发送原始图像而不进行压缩或修改。
我尝试了Thread.sleep(5000);
我也尝试过以下操作,但问题是它在上传之前清理了我的Bitmap,因为它的异步
bm.recycle(); bm = null;
无论如何我可以上传图片ONE BY ONE
@Override
protected void onCreate(Bundle savedInstanceState) {
picturePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()+"/Camera/";
Log.d("Files", "Path: " + picturePath);
File f = new File(picturePath);
File file[] = f.listFiles();
Log.d("Files", "Size: " + file.length);
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName:" + file[i].getName());
// Image location URL
Log.e("Files", "----------------" + picturePath+file[i].getName());
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath + file[i].getName());
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 75, bao);
byte[] ba = bao.toByteArray();
ba1 = Base64.encodeToString(ba, Base64.DEFAULT);
Log.d("Files", "Uploading");
new uploadToServer().execute();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("Files", "In the try Loop" + st);
} catch (Exception e) {
Log.v("Files", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
答案 0 :(得分:1)
您需要使用HttpUrlConnection的.setChunkedStreamingMode(1024);
请参阅此answer以获取示例