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

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(使用前将#替换为@)

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

  • android 中的自定义 MediaPlayer 类

    我刚刚完成了一个项目 我使用网络视图进行视频播放 现在我被要求用自定义播放器替换 webview 部分 玩家应该能够处理 HLS 如果我使用VideoView和MediaController 我可以播放直播 但不幸的是 MediaContr
  • 删除 JSON 属性 [重复]

    这个问题在这里已经有答案了 如果我有一个 JSON 对象 请说 var myObj test key1 value key2 value 我可以删除 key1 使其变为 test key2 value Simple delete myObj
  • 设备管理员禁用

    如果不是 则无法卸载设备管理应用程序 禁用 用户可以从设置中禁用 设备管理员 当公司向员工提供 Android 设备时 公司希望 可以控制设备及其状态和策略 但用户可以 轻松摆脱这种控制 有谁知道这怎么可能 防止用户禁用设备管理员 谢谢 无
  • 使用自定义 cordova 插件未找到类异常

    我正在开发一个打印应用程序 它使用自定义 API 通过 USB 访问打印机 因此我需要一个自定义 Cordova 插件 我开始开发它 这是一个非常好的挑战 但目前也非常令人沮丧 因为我不明白为什么我的插件不能正确使用 事情是 1 插件安装正
  • 两个外部第三方混淆库中存在重复的类名

    我有一个项目 其中包含两个外部第三方库 当尝试构建项目时 这两个库的类文件名都被混淆了 并且 gradle barfs 了 Duplicate class a a a a a b found in modules 我无法排除任何类 因为它们
  • 剃须刀付款给予 未发现合适的付款方式错误

    所以我正在实现这个简单的剃 刀支付集成 但它给了我一个 找不到合适的付款方式 错误 我之前尝试过选择付款选项表格 但也不起作用 val razorpay RazorpayClient my key my secret key val ord
  • Android 版 OpenGL ES 中的透明纹理

    我试图在 opengl 中设置四边形上纹理的透明度 使用混合函数没有帮助 谷歌上也没有任何帮助 有什么建议么 我遇到了类似的问题 一段代码可以正常工作 而另一段则不能 经过大量的日志记录和调试 我发现差异只是一行代码 在具有工作 Alpha
  • 适用于 Web 和移动设备的 ASP.NET Web API 社交身份验证

    我的问题有点复杂 所以请耐心等待我 因为我试图很好地阐明我正在努力解决的问题 Goal 拥有一个 ASP NET 网站 允许用户通过用户名 密码或也具有 API 的社交网站 Facebook Twitter Google 等 注册和登录 该
  • Android 上下文不在活动中?还有其他无活动编程吗?

    我会非常努力地将其变成一个综合问题 我正在编写一个方法来获取一个包含 Android 设备城市名称的字符串 该名称由LocationManager and getLastKnownLocation 等等 然后我意识到我需要在另一个活动中再次
  • 在具有循环依赖关系的大型对象上调用 JSON.stringify 时出现“太多递归”错误

    我有一个包含循环引用的对象 我想查看它的 JSON 表示形式 例如 如果我构建这个对象 var myObject member myObject member child myObject member child parent myObj
  • 如何在 API 级别 8 到 19 的 Android 设备上同时使用 DigitalClock 和 TextClock?

    我正在为 API 级别 8 到 19 的设备制作应用程序 其中包含时钟 我尝试将 DigitalClock 进行布局 我从 Eclipse 收到消息 该类自 API 级别 17 起已弃用 建议使用 TextClock 但是当我放置 Text
  • Android 设备中未显示背景图片?

    我将以下代码添加到main xml将图像设置为我的应用程序的背景图像 android background drawable bg So main xml看起来像这样
  • JSch:如何使用 ssh 密钥 ssh 到服务器

    我想从另一个 ssh 服务器后面 ssh 进入服务器 网关服务器需要用户名 密码 我可以做到这一点 我正在使用隧道进入下一台服务器 但这需要only一个 ssh 密钥 我已经通过 PuTTY 生成了密钥 因此它存在于我的用户名中 但我不确定
  • Eclipse java 断点 - 目的是什么?

    我正在学习 Android 教程 刚刚进入调试部分 我想知道断点的用途是什么 我还不能告诉 它实际上停止了应用程序 以便我可以确定它运行到该点 或者我可以设置多个断点并将它们用作标记来从断点到断点检查 停止和运行 我的代码 断点是执行停止的
  • Android:需要记录麦克风输入

    有没有办法在实时播放 预览过程中记录 Android 中的麦克风输入 我尝试使用AudioRecord and AudioTrack这样做 但问题是我的设备无法播放录制的音频文件 实际上 任何Android播放器应用程序都无法播放录制的音频
  • 加载远程图像

    在 Android 中 最简单的方法是什么 从远程服务器加载图像 将其显示在 ImageView 中 这是我在应用程序中实际使用的方法 我知道它有效 try URL thumb u new URL http www example com
  • 使用“是/否”对话框拦截链接 LinkMovementMethod

    我有一个标准LinkMovementMethod https developer android com reference android text method LinkMovementMethod建立在我的TextView当用户触摸链
  • 如何创建带有两个日期选择器的自定义对话框?

    我刚刚开始学习 Android 作为一种爱好 我想创建一个带有两个日期选择器的对话框 final Dialog dialog new Dialog this dialog setContentView R layout data picke
  • 除了前一个按钮意图之外,如何添加另一个按钮意图?

    这是我的代码 它包含一个名为的按钮button1A当我单击它时 它会打开一个名为的列表list1 如何为另一个名为 button2A 的按钮添加代码 该按钮将打开一个列表 List2 import android os Bundle imp
  • 如何在 C# 中将 json 转换为平面结构

    我正在尝试用 C 编写函数 将 JSON 转换为键 值对 它应该支持数组 例如下面的 JSON title title value components component id id1 menu title menu title1 tit

随机推荐