如何使用多部分实体将图像上传到服务器?

2023-12-15

我正在创建一个应用程序,并在我的应用程序中添加了一个选项来从图库浏览图像,然后上传到服务器,我之前问过这个问题,但没有得到好的答案,为了上传图像,我正在遵循本教程http://mayanklangalia.blogspot.in/2014/04/how-to-upload-multiple-images-on-php.html下面我发布了我的代码,任何人都可以帮助我。

enter image description here enter image description here enter image description here

public class PhotoUpload extends Activity{
private Button upload, pick;
private ProgressDialog dialog;
MultipartEntity entity;
GridView gv;
int count = 0;
String matchId;
ArrayList<String> ImgData;
public ArrayList<String> map = new ArrayList<String>();
Bundle b;
TextView noImage;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photos_upload);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);

    b = getIntent().getExtras();

    matchId=this.getIntent().getStringExtra("id");
    System.out.println(matchId);
    noImage = (TextView) findViewById(R.id.noImage);
    upload = (Button) findViewById(R.id.btnUpload);
    pick = (Button) findViewById(R.id.btnPicture);
    gv = (GridView) findViewById(R.id.gridview);
    gv.setAdapter(new ImageAdapter(this));

    if (b != null) {
        ImgData = b.getStringArrayList("IMAGE");
        for (int i = 0; i < ImgData.size(); i++) {
            map.add(ImgData.get(i).toString());
        }
    } else {
        noImage.setVisibility(View.VISIBLE);
    }

    upload.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            new ImageUploadTask()
                    .execute(count + "", "pk" + count + ".jpg");
        }
    });

    pick.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Intent i3 = new Intent(PhotoUpload.this, UploadActivity.class);
            startActivity(i3);
        }
    });

}

class ImageUploadTask extends AsyncTask<String, Void, String> {

    String sResponse = null;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog = ProgressDialog.show(PhotoUpload.this, "Uploading",
                "Please wait...", true);
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            String url = "http://mnbmnbnmb.com/webservice/addphoto?version=apps&user_login_id="+matchId+"&image_1="+ImgData+"&action=save";
            int i = Integer.parseInt(params[0]);
            Bitmap bitmap = decodeFile(map.get(i));
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            entity = new MultipartEntity();

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();

            entity.addPart("user_login_id", new StringBody("199"));
            entity.addPart("image_1", new StringBody("10"));
            entity.addPart("action", new ByteArrayBody(data,
                    "image/jpeg", params[1]));

            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost,
                    localContext);
            sResponse = EntityUtils.getContentCharSet(response.getEntity());

            System.out.println("sResponse : " + sResponse);
        } catch (Exception e) {
            if (dialog.isShowing())
                dialog.dismiss();
            Log.e(e.getClass().getName(), e.getMessage(), e);

        }
        return sResponse;
    }

    @Override
    protected void onPostExecute(String sResponse) {
        try {
            if (dialog.isShowing())
                dialog.dismiss();

            if (sResponse != null) {
                Toast.makeText(getApplicationContext(),
                        sResponse + " Photo uploaded successfully",
                        Toast.LENGTH_SHORT).show();
                count++;
                if (count < map.size()) {
                    new ImageUploadTask().execute(count + "", "hm" + count
                            + ".jpg");
                }
            }

        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }

    }
}

public Bitmap decodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);
    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;
    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
    return bitmap;
}

private class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return map.size();
    }

    public Object getItem(int position) {
        return null;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) { // if it's not recycled, initialize some
                                    // attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85,
                    Gravity.CENTER));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setPadding(1, 1, 1, 1);

        } else {
            imageView = (ImageView) convertView;
        }

        imageView
                .setImageBitmap(BitmapFactory.decodeFile(map.get(position)));
        return imageView;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    PhotoUpload.this.finish();  
}
}

上传活动.java

public class UploadActivity extends Activity{

private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
private static final int PICK_FROM_CAMERA = 1;
ArrayList<String> IPath = new ArrayList<String>();
public static Uri uri;

/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    final String[] columns = { MediaStore.Images.Media.DATA,
            MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    Cursor imagecursor = managedQuery(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);
    int image_column_index = imagecursor
            .getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.thumbnails = new Bitmap[this.count];
    this.arrPath = new String[this.count];
    this.thumbnailsselection = new boolean[this.count];
    for (int i = 0; i < this.count; i++) {
        imagecursor.moveToPosition(i);
        int id = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor
                .getColumnIndex(MediaStore.Images.Media.DATA);
        thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                getApplicationContext().getContentResolver(), id,
                MediaStore.Images.Thumbnails.MICRO_KIND, null);
        arrPath[i] = imagecursor.getString(dataColumnIndex);
    }
    GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imageAdapter = new ImageAdapter();
    imagegrid.setAdapter(imageAdapter);
    imagecursor.close();



    final Button uploadBtn = (Button) findViewById(R.id.uploadDONE);
    uploadBtn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            final int len = thumbnailsselection.length;
            int cnt = 0;
            String selectImages = "";
            for (int i = 0; i < len; i++) {
                if (thumbnailsselection[i]) {
                    cnt++;
                    selectImages = arrPath[i];
                    IPath.add(selectImages);
                }
            }

            if (cnt == 0) {
                Toast.makeText(getApplicationContext(),
                        "Please select at least one image",
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "You've selected Total " + cnt + " image(s).",
                        Toast.LENGTH_LONG).show();
                Log.d("SelectedImages", selectImages);



                Intent intentMessage = new Intent(UploadActivity.this,
                        PhotoUpload.class);
                intentMessage.putStringArrayListExtra("IMAGE", IPath);
                startActivity(intentMessage);
            }
        }
    });
}

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return count;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.galleryitem, null);
            holder.imageview = (ImageView) convertView
                    .findViewById(R.id.thumbImage);
            holder.checkbox = (CheckBox) convertView
                    .findViewById(R.id.itemCheckBox);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.checkbox.setId(position);
        holder.imageview.setId(position);
        holder.checkbox.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                CheckBox cb = (CheckBox) v;
                int id = cb.getId();
                if (thumbnailsselection[id]) {
                    cb.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    cb.setChecked(true);
                    thumbnailsselection[id] = true;
                }
            }
        });



        holder.imageview.setImageBitmap(thumbnails[position]);
        holder.checkbox.setChecked(thumbnailsselection[position]);
        holder.id = position;
        return convertView;
    }
}

class ViewHolder {
    ImageView imageview;
    CheckBox checkbox;
    int id;
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    Intent i = new Intent(UploadActivity.this, MainActivity.class);
    UploadActivity.this.finish();
    startActivity(i);
    super.onBackPressed();
}

}

我使用此代码将文件上传到服务器:(如果我正确理解你的问题)

首先选择文件
在选择图像按钮侦听器中运行此方法之一:

从图库中选择照片:

 void startImagePicker() {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_SEND_IMAGE); 
        }

用相机拍照:

void startPhotoTaker() {

        // create Intent to take a picture and return control to the calling application
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "cs_" + new Date().getTime() + ".jpg");
        mLastPhoto = Uri.fromFile(photo);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                mLastPhoto);

        // start the image capture Intent
        startActivityForResult(intent, REQUEST_TAKE_PICTURE);
    }

从文件管理器中选择任何文件:

void startFilePicker() {
        Intent selectFile = new Intent(Intent.ACTION_GET_CONTENT);
        selectFile.setType("file/*");
        Intent intentChooser = Intent.createChooser(selectFile, "Select File");

        if (intentChooser != null)
            startActivityForResult(Intent.createChooser(selectFile, "Select File"), REQUEST_SEND_FILE);
    }

在您的 onActivityForResault 方法中复制以下内容:

在 onActivityResult 中:

if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_SEND_IMAGE) {
                Uri uri = resultIntent.getData();
                if (uri == null) {
                    return;
                }
                File file = new File(getRealPathFromURI(uri));
                final Handler handler = new Handler();
                MediaScannerConnection.scanFile(
                        this, new String[]{file.toString()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, final Uri uri) {

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadFile(uri);
                                    }
                                });
                            }
                        });
            } else if (requestCode == REQUEST_SEND_FILE |) {
                Uri uri = resultIntent.getData();
                if (uri == null) {
                    return;
                }

                uploadFile(uri);
            } else if (requestCode == REQUEST_TAKE_PICTURE) {

                File file = new File(getRealPathFromURI(mLastPhoto));
                final Handler handler = new Handler();
                MediaScannerConnection.scanFile(
                        this, new String[]{file.toString()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, final Uri uri) {

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadFile(mLastPhoto);
                                    }
                                });
                            }
                        });

            } 
        }

上传文件到服务器:

private String uploadFile(Uri resourceUri) {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        final File sourceFile = new File(getRealPathFromURI(resourceUri));
        String serverResponseMessage = null;
        String responce = null;
        if (!sourceFile.isFile()) {

            dialog.dismiss();

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "File not found !", Toast.LENGTH_LONG).show();
                }
            });

            return "no file";
        } else {
            try {
                FileInputStream fileInputStream = new FileInputStream(sourceFile.getPath());
                URL url = new URL("your upload server/API url");
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty(POST_FIELD, sourceFile.getName());
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"" + POST_FIELD + "\";filename="
                        + sourceFile.getName() + lineEnd);
                dos.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                int serverResponseCode = conn.getResponseCode();
                serverResponseMessage = conn.getResponseMessage();
                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);
                if (serverResponseCode <= 200) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            Toast.makeText(PreviewActivity.this, "File Upload Complete.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                fileInputStream.close();
                dos.flush();
                dos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (MalformedURLException ex) {
                dialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {

                        Toast.makeText(PreviewActivity.this, "MalformedURLException",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (IOException e) {
                dialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(PreviewActivity.this, "Got Exception : see logcat ",
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception", "Exception : "
                        + e.getMessage(), e);
            }
        }
        dialog.dismiss();
        return responce;
    }  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用多部分实体将图像上传到服务器? 的相关文章

  • 卸载后 Web 应用程序不显示“添加到主屏幕”

    这是我第一次创建网络应用程序 我设法解决了这个问题 所以我得到了实际的 chrome 提示 将其添加到主屏幕 然后我从手机上卸载了该网络应用程序 因为我想将其展示给我的同事 但是 屏幕上不再出现提示 问题 这是有意为之的行为还是我的应用程序
  • Adobe 是否为其 PDF 阅读器提供 Android SDK 或 API? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我希望能够在我们的应用程序内的视图中显示本地 PDF 文件 在 Android 4 03 下的平板电脑上运行 目前 我们将 Adob eR
  • Android 模拟器插件无法初始化后端 EGL 显示

    我在 Cloudbees 上设置了 Jenkins 作业 并且可以在那里成功签出并编译我的 Android 项目 现在我想在 android 模拟器中运行一些 JUnit 测试并添加 Android 模拟器插件 我将 显示模拟器窗口 选项设
  • 是否必须删除 Intent extra?

    这可能是一个愚蠢的问题 但是是否有一条规则规定消费活动必须显式删除 Intent 额外内容 或者只有在回收 Intent 对象时才如此 换句话说 如果我总是通过执行以下操作来链接到下一个活动 Intent i new Intent MyCu
  • 无法访问 com.google.android.gms.internal.zzbfm 的 zzbfm 类文件未找到

    我正在将我的 Android 应用程序项目从GCM to FCM 为此 我使用 Android Studio 中的 Firebase 助手工具 并遵循 Google 开发人员指南中的说明 一切都很顺利 并将我的应用程序代码更改为FCM根据助
  • 尝试将相机切换回前面但出现异常

    尝试将相机切换回前面 但出现异常 找不到 问题请检查并帮助 error 01 27 11 49 00 376 E AndroidRuntime 30767 java lang RuntimeException Unable to start
  • 在gradle插件中获取应用程序变体的包名称

    我正在构建一个 gradle 插件 为每个应用程序变体添加一个新任务 此新任务需要应用程序变体的包名称 这是我当前的代码 它停止使用最新版本的 android gradle 插件 private String getPackageName
  • JavaMail 只获取新邮件

    我想知道是否有一种方法可以在javamail中只获取新消息 例如 在初始加载时 获取收件箱中的所有消息并存储它们 然后 每当应用程序再次加载时 仅获取新消息 而不是再次重新加载它们 javamail 可以做到这一点吗 它是如何工作的 一些背
  • 在 SQLite 中搜索时排除 HTML 标签和一些 UNICODE 字符

    更新 4 我已经成功运行了firstchar例如 但现在的问题是使用regex 即使包含头文件 它也无法识别regex操作员 有什么线索可以解决这个问题吗 更新 2 我已经编译了sqlite3我的项目中的库 我现在正在寻找任何人帮助我为我的
  • jQuery AJAX 请求在 IE8 中失败,并显示消息“错误:调用 open 方法之前无法调用此方法。”

    我正在使用 jQuery 1 4 2 并尝试执行一个简单的 AJAX 请求 目标 URL 返回一个 JSON 字符串 我使用 jslint 对其进行了验证 该请求在 Firefox 和 Chrome 中有效 但不想在 IE8 中工作 我无法
  • 如何使用InputConnectionWrapper?

    我有一个EditText 现在我想获取用户对此所做的所有更改EditText并在手动将它们插入之前使用它们EditText 我不希望用户直接更改中的文本EditText 这只能由我的代码完成 例如通过使用replace or setText
  • Android Studio - Windows 7 上的 Android SDK 问题

    我对 Google i o 2013 上发布的最新开发工具 Android Studio 有疑问 我已经成功安装了该程序并且能够正常启动 我可以导入现有项目并对其进行编辑 但是 当我尝试单击 SDK 管理器图标或 AVD 管理器图标时 或者
  • 使用 x509 证书签署 json 文档或字符串

    如何使用 x509 证书签署 json 文档或字符串 public static void fund string filePath C Users VIKAS Desktop Data xml Read the file XmlDocum
  • 增加活动的屏幕亮度

    显然 Android 操作系统中至少有三种不同的技术可以改变屏幕亮度 其中两个在纸杯蛋糕之后不再起作用 而第三个被接受的技术显然有一个错误 我想在单视图活动开始时增加屏幕亮度 然后在活动结束时将亮度恢复为用户设置 没有按钮 没有第二个视图或
  • GitHub Actions:如何将 toJSON() 结果传递给 shell 命令

    因此 我正在与 Github Actions 合作进行端到端测试 我正在查看的设置是让一项作业检索要测试的 url 列表 而我的第二项作业使用该列表创建一个矩阵并测试所有这些 我的问题是 当我实际运行测试脚本时 必须从命令行完成 因为我使用
  • 实现滚动选择 ListView 中的项目

    我想使用 ListView 您可以在其中滚动列表来选择一个项目 它应该像一个 Seekbar 但拇指应该是固定的 并且您必须使用该栏来调整它 我面临的一个问题是 我不知道这种小部件是如何调用的 这使得我很难搜索 所以我制作了下面这张图片 以
  • Firebase 添加新节点

    如何将这些节点放入用户节点中 并创建另一个节点来存储帖子 我的数据库参考 databaseReference child user getUid setValue userInformations 您需要使用以下代码 databaseRef
  • 将 Intent 包装在 LabeledIntent 中以用于显示目的

    要求 我的应用程序中有一个 共享 按钮 我需要通过 Facebook 分享 我需要选择是否安装原生 Facebook 应用程序 我们的决定是 如果未安装该应用程序 则将用户发送到 facebook com 进行分享 当前状态 我可以检测何时
  • Crashlytics 出现 Android Studio 构建错误

    我正在尝试将 CrashLytics 与 Android Studio 和 gradle 一起使用 但出现一个令人困惑的错误 java lang NoSuchMethodError 我的 build gradle 是 buildscript
  • 强制 Listview 不重复使用视图(复选框)

    我做了一个定制Listview 没有覆盖getView 方法 Listview 中的每个项目都具有以下布局 联系布局 xml

随机推荐