我在服务器上传了多张图片,我有一种上传单张图片到服务器的方法。现在,我正在使用此方法通过为每个图像创建循环来发送多个图像。
有没有最快的方式将多个图像发送到服务器?提前谢谢......
public int imageUpload(GroupInfoDO infoDO) {
ObjectMapper mapper = new ObjectMapper();
int groupId = 0;
try {
Bitmap bm = BitmapFactory.decodeFile(infoDO.getDpUrl());
String fileName = infoDO.getDpUrl().substring(
infoDO.getDpUrl().lastIndexOf('/') + 1,
infoDO.getDpUrl().length());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://192.168.1.24:8081/REST/groupreg/upload");
ByteArrayBody bab = new ByteArrayBody(data,
"application/octet-stream");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploadFile", bab);
reqEntity.addPart("name", new StringBody(fileName));
reqEntity.addPart("grpId", new StringBody(infoDO.getGlobalAppId()
+ ""));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
String json = EntityUtils.toString(httpEntity);
Map<String, Object> mapObject = mapper.readValue(json,
new TypeReference<Map<String, Object>>() {
});
if ((mapObject != null)
&& (mapObject.get("status").toString()
.equalsIgnoreCase("SUCCESS"))) {
groupId = (Integer.valueOf(mapObject.get("groupId")
.toString()));
}
}
} catch (Exception e1) {
e1.printStackTrace();
Log.e("log_tag", "Error in http connection " + e1.toString());
}
return groupId;
}
答案 0 :(得分:5)
有很多方法可以将更多图像上传到服务器..一个可能包括两个库:apache-mime4j-0.6.jar和httpmime-4.0.1.jar ..之后创建你的java主代码:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
}
现在你的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Multiple File Upload from CoderzHeaven"
/>
<Button
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get First File">
</Button>
<Button
android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Second File">
</Button>
<Button
android:id="@+id/upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Upload">
</Button>
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Selected File path : "
/>
<TextView
android:id="@+id/res"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
当然,在您的清单中包含互联网权限:
<uses-permission android:name="android.permission.INTERNET" />
瞧瞧。无论如何,我在我的情况下遵循了这个例子:http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/尝试看到那里..有4种方法可以上传多个文件。看看你喜欢哪个
答案 1 :(得分:2)
使用Volley
stash_json
答案 2 :(得分:1)
试试这段代码。这对于一次或两次或三次图片上传很有用,并使用httpmime-4.2.1.jar
<强>活动强>
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class MultiImageActivity extends Activity {
private static final int CAMERA_PICTURE = 1;
private static final int GALLERY_PICTURE = 2;
String filePath1 = null;
String filePath2 = null;
String filePath3 = null;
Bitmap chosenImage;
File destination = null;
ImageView ivImg1, ivImg2, ivImg3;
String img1Selected1 = null, img2Selected1 = null, img3Selected1 = null;
String img1Selected2 = null, img2Selected2 = null, img3Selected2 = null;
LinearLayout llImgHolder;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multi_image);
Button btnImg1 = (Button) findViewById(R.id.btn_multi_img_1);
Button btnImg2 = (Button) findViewById(R.id.btn_multi_img_2);
Button btnImg3 = (Button) findViewById(R.id.btn_multi_img_3);
Button btnUpload = (Button) findViewById(R.id.btn_multi_upload);
llImgHolder = (LinearLayout) findViewById(R.id.ll_multi_img_holder);
ivImg1 = (ImageView) findViewById(R.id.iv_multi_img1);
ivImg2 = (ImageView) findViewById(R.id.iv_multi_img2);
ivImg3 = (ImageView) findViewById(R.id.iv_multi_img3);
btnImg1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
img1Selected1 = "fulfilled";
choosePictureAction();
}
});
btnImg2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (img1Selected2 != null) {
img2Selected1 = "fulfilled";
choosePictureAction();
}else {
Log.e("Please select first image", "Please select first image");
}
}
});
btnImg3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (img2Selected2 != null) {
img3Selected1 = "fulfilled";
choosePictureAction();
}else {
Log.e("Please select second image", "Please select second image");
}
}
});
btnUpload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String url="______________your_api________";
new uploadAsynTask().execute(url);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PICTURE && resultCode == RESULT_OK) {
chosenImage = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
chosenImage.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
//filePath1 = destination.toString();
if(img1Selected1 != null){
filePath1 = destination.toString();
}else if(img2Selected1 != null){
filePath2 = destination.toString();
}else if(img3Selected1 != null){
filePath3 = destination.toString();
}
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(chosenImage != null){
if(img1Selected1 != null){
llImgHolder.setVisibility(View.VISIBLE);
ivImg1.setVisibility(View.VISIBLE);
img1Selected1 = null;
img1Selected2 = "fulfilled";
ivImg1.setImageBitmap(chosenImage);
}else if(img2Selected1 != null){
ivImg2.setVisibility(View.VISIBLE);
img2Selected1 = null;
img2Selected2 = "fulfilled";
ivImg2.setImageBitmap(chosenImage);
}else if(img3Selected1 != null){
ivImg3.setVisibility(View.VISIBLE);
img3Selected1 = null;
img3Selected2 = "fulfilled";
ivImg3.setImageBitmap(chosenImage);
}
}
} else if (requestCode == CAMERA_PICTURE
&& resultCode == RESULT_CANCELED) {
} else if (requestCode == GALLERY_PICTURE
&& resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String[] projection = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
destination = new File(selectedImagePath);
if(img1Selected1 != null){
filePath1 = selectedImagePath;
}else if(img2Selected1 != null){
filePath2 = selectedImagePath;
}else if(img3Selected1 != null){
filePath3 = selectedImagePath;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
chosenImage = BitmapFactory.decodeFile(selectedImagePath, options);
if(chosenImage!=null){
if(img1Selected1 != null){
llImgHolder.setVisibility(View.VISIBLE);
ivImg1.setVisibility(View.VISIBLE);
img1Selected1 = null;
img1Selected2 = "fulfilled";
ivImg1.setImageBitmap(chosenImage);
}else if(img2Selected1 != null){
ivImg2.setVisibility(View.VISIBLE);
img2Selected1 = null;
img2Selected2 = "fulfilled";
ivImg2.setImageBitmap(chosenImage);
}else if(img3Selected1 != null){
ivImg3.setVisibility(View.VISIBLE);
img3Selected1 = null;
img3Selected2 = "fulfilled";
ivImg3.setImageBitmap(chosenImage);
}
}
} else if (requestCode == GALLERY_PICTURE
&& resultCode == RESULT_CANCELED) {
}
}
private void choosePictureAction(){
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MultiImageActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(items[which].equals("Camera")){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PICTURE);
}else if(items[which].equals("Gallery")){
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_PICTURE);
}else if(items[which].equals("Cancel")){
dialog.dismiss();
}
}
});
builder.show();
}
private class uploadAsynTask extends AsyncTask<String, Void, String>{
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(MultiImageActivity.this, null, null);
ProgressBar spinner = new android.widget.ProgressBar(MultiImageActivity.this, null,android.R.attr.progressBarStyle);
spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#009689"), android.graphics.PorterDuff.Mode.SRC_IN);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(spinner);
dialog.setCancelable(false);
dialog.show();
}
@Override
protected String doInBackground(String... params) {
Log.e("FilePathBin1", filePath1);
File file1 = new File(filePath1);
File file2 = null;
File file3 = null;
if(img2Selected2 != null){
Log.e("FilePathBin2", filePath2);
file2 = new File(filePath2);
}
if(img3Selected2 != null){
Log.e("FilePathBin3", filePath3);
file3 = new File(filePath3);
}
MultipartEntity reqEntity;
HttpEntity resEntity;
try {
HttpClient client = new DefaultHttpClient();
String postURL = params[0];
HttpPost post = new HttpPost(postURL);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = null;
FileBody bin3 = null;
if(img2Selected2 != null){
bin2 = new FileBody(file2);
}
if(img3Selected2 != null){
bin3 = new FileBody(file3);
}
reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("parking_title", new StringBody("Test13:26"));
reqEntity.addPart("latitude", new StringBody("10.12313213"));
reqEntity.addPart("longtitude", new StringBody("12.123213213"));
reqEntity.addPart("note", new StringBody("12"));
reqEntity.addPart("filename[0]", bin1);
if(img2Selected2 != null){
img2Selected2 = null;
reqEntity.addPart("filename[1]", bin2);
}
if(img3Selected2 != null){
img3Selected2 = null;
reqEntity.addPart("filename[2]", bin3);
}
reqEntity.addPart("spot_types[0]", new StringBody("1"));
reqEntity.addPart("spot_types[1]", new StringBody("2"));
reqEntity.addPart("spot_types[2]", new StringBody("3"));
reqEntity.addPart("spot_properties[0]", new StringBody("1"));
reqEntity.addPart("spot_properties[1]", new StringBody("2"));
reqEntity.addPart("spot_properties[2]", new StringBody("3"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
String entityContentAsString = EntityUtils.toString(resEntity);
Log.d("stream:", entityContentAsString);
return entityContentAsString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
dialog.dismiss();
Log.e("addPhotoResult", result);
filePath1 = null;
filePath2 = null;
filePath3 = null;
try {
JSONObject jsonObject = new JSONObject(result);
String error = jsonObject.getString("Error");
String message = jsonObject.getString("message");
Log.e("error", error);
Log.e("message", message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Xml布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context="com.app.multiimage.MultiImageActivity" >
<Button
android:id="@+id/btn_multi_img_1"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#000000"
android:text="@string/multi_img1"
android:textColor="#FFFFFF"
android:textSize="12sp" />
<Button
android:id="@+id/btn_multi_img_2"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_below="@+id/btn_multi_img_1"
android:layout_marginTop="10dp"
android:background="#000000"
android:text="@string/multi_img2"
android:textColor="#FFFFFF"
android:textSize="12sp" />
<Button
android:id="@+id/btn_multi_img_3"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_below="@+id/btn_multi_img_2"
android:layout_marginTop="10dp"
android:background="#000000"
android:text="@string/multi_img3"
android:textColor="#FFFFFF"
android:textSize="12sp" />
<LinearLayout
android:id="@+id/ll_multi_img_holder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_multi_img_3"
android:layout_marginTop="10dp"
android:visibility="gone"
android:orientation="horizontal" >
<ImageView
android:id="@+id/iv_multi_img1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_weight="1"
android:visibility="gone"
android:contentDescription="@string/empty" />
<ImageView
android:id="@+id/iv_multi_img2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_toRightOf="@+id/iv_multi_img1"
android:layout_weight="1"
android:visibility="gone"
android:contentDescription="@string/empty" />
<ImageView
android:id="@+id/iv_multi_img3"
android:layout_width="100dp"
android:layout_height="100dp"
android:visibility="gone"
android:layout_toRightOf="@+id/iv_multi_img2"
android:layout_weight="1"
android:contentDescription="@string/empty" />
</LinearLayout>
<Button
android:id="@+id/btn_multi_upload"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_below="@+id/ll_multi_img_holder"
android:layout_marginTop="10dp"
android:background="#000000"
android:text="@string/multi_upload"
android:textColor="#FFFFFF"
android:textSize="12sp" />
</RelativeLayout>
<强>清单强>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />