在android中上传多个图像到服务器的最快方法

2023-11-20

我有多个图像要在服务器中上传,并且我有一种将单个图像上传到服务器的方法。现在我使用此方法通过为每个图像创建循环来发送多个图像。

有没有最快的方法将多个图像发送到服务器?提前致谢...

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;
    } 

有很多方法可以将更多图像上传到服务器。其中一种可以包含两个库: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 种上传多个文件的方法。看看你喜欢哪个

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在android中上传多个图像到服务器的最快方法 的相关文章

随机推荐

  • __printflike__ 修饰符

    printflike 修饰符 到底是什么 这个词是什么意思 据猜测 它告诉编译器您正在使用的函数采用以下形式的参数 anything format 哪里的format 部分看起来像参数printf The printflike 属性允许编译
  • 像 Google 使用的滚动条

    随着 Google 推出的最新更新 所有网站都获得了自定义 JS 滚动条 至少在 Chrome 中 我最喜欢它的一点是它简单且运行完美 到目前为止 我见过的很多 JS 滚动条都不能很好地工作 也就是说 如果你滚动得非常快或者滚动并移动鼠标
  • Jquery 延迟加载与 ajax

    我在我的电子商务网站上使用lazyload 惰性加载 效果很好 我使用这段代码来做到这一点 function img lazy lazyload effect fadeIn 还有一些过滤器 如颜色 价格等 运行 ajax 并显示新结果 当新
  • SwiftUI/Combine:订阅@Binding的值变化

    我有一个带有视图模型的视图 该视图中的操作可以更改视图模型 为了能够将逻辑分解为可重用的部分 我将视图的一部分作为其自己的视图 并对其所需的值使用 Binding 现在 我希望能够根据值更改执行一些逻辑 而不必只是视图更改 我怎样才能做到这
  • 如何使用多个命令启动 cmd.exe /k?

    为什么下面的代码不改变颜色和标题cmd2 怎么做以及做什么 该命令改变颜色cmd1 并将标题设置为cmd2 start cmd exe k TITLE TEST color 02 mode con cols 160 lines 78 sta
  • Android 序列化问题

    我创建了一个类 它有几个成员变量 所有这些变量都是可序列化的 除了一个位图 我尝试扩展位图并实现可序列化 但不认为位图是最终类 我想保存该类 它基本上构成了游戏的当前状态 以便玩家可以拾取并加载游戏 在我看来 我有两个选择 1 寻找另一种保
  • 如何为 java HttpURLConnection 流量启用线路日志记录?

    我用过雅加达公共 HttpClient在另一个项目中 我也想要同样的电线记录输出但使用 标准 HttpUrlConnection 我用过Fiddler作为代理 但我想直接从 java 记录流量 捕获连接输入和输出流的内容是不够的 因为 HT
  • 如何根据 Wavefront (.obj) 文件中给出的纹理索引对纹理位置进行排序?

    我目前正在尝试为 OpenGL 项目制作一个 Wavefront obj 文件加载器 我当前使用的方法是逐行分离向量 std vectors 中的顶点位置 纹理位置和法线位置 并且我将它们的索引 顶点 纹理和法线索引 存储在三个单独的文件中
  • Kivy ObjectProperty 更新标签文本

    我正在创建一个 kivy 用户界面来显示由我编写为标准 python 对象的数据模型生成的值 本质上 我希望用户能够按下一个按钮 这将更改底层数据模型 并且此更改的结果将自动更新和显示 据我了解 这可以使用 kivy 属性 在本例中为 Ob
  • 允许Html不工作

    我正在构建一个内容管理系统 以允许我以外的人更新网站上的内容 我有一个前端 HTML 表单 它通过 AJAX 将数据发送到控制器 CONTROLLER ValidateInput false public void CarAJAX CarA
  • 获取文本框值的VBA/宏代码

    Sub CopyRandomRows Windows sample rnd xlsm Activate Rows 1 1 Select Selection Copy Application CutCopyMode False Selecti
  • AWS/EKS:从 ALB 频繁收到 504 网关超时错误

    我正在使用 EKS 部署服务 入口在 alb ingress controller 之上运行 总而言之 我有大约 10 个单个 Pod 的副本 具有单一服务类型NodePort它将流量转发给他们 副本在 10 个节点上运行 使用 eksct
  • 检测用于 HttpClient POST 或 GET 调用的 TLS 版本

    我正在尝试检索 TLS 版本信息 下面的代码使用 HttpClient 成功进行了 HTTP GET 调用 我缺少什么 我在哪里可以从 HttpClient 获取 TLS 版本信息 我正在做与建议相同的事情协商了哪个 TLS 版本 但这是特
  • 获取已打印的python文本内容

    假设我打印以下代码 print THE RUSSIAN PEASANT ALGORITHM times two values x and y together x int raw input raw input x y int raw in
  • 如何使用 jQuery 加载本地文件? (带有文件://)

    有没有办法使用 jQuery 从数据文件 例如 JSON js 文件 加载数据 eg get file C objectData js function alert Load was performed 目前 JQuery 似乎没有执行简单
  • 将 Graph API 中 Facebook 访问令牌的有效期延长至 2 个月以上

    我正在使用 python 开发 Facebook 页面墙贴自动化 我通过使用自动在我拥有的 Facebook 页面上发帖Facebook 图表 API 帖子所以我通过发送 HTTP POST 请求来做到这一点https graph face
  • System V IPC 与 POSIX IPC

    两者有什么区别System V IPC and POSIX IPC 为什么我们有两个标准 如何决定使用哪些IPC功能 两者都有相同的基本工具 信号量 共享内存和消息队列 它们提供的界面与这些工具略有不同 但基本概念是相同的 一个显着的区别是
  • 如何转义 WPF 绑定路径中的斜杠字符,或者如何解决?

    我刚刚学习 WPF 我将一个表从数据源拖到一个为每列生成 XAML 的窗口上 其中一些列的名称会导致以下情况
  • 如何反汇编原始 16 位 x86 机器代码?

    我想反汇编我拥有的可启动 x86 磁盘的 MBR 前 512 字节 我已使用以下命令将 MBR 复制到文件中 dd if dev my device of mbr bs 512 count 1 对可以反汇编该文件的 Linux 实用程序的任
  • 在android中上传多个图像到服务器的最快方法

    我有多个图像要在服务器中上传 并且我有一种将单个图像上传到服务器的方法 现在我使用此方法通过为每个图像创建循环来发送多个图像 有没有最快的方法将多个图像发送到服务器 提前致谢 public int imageUpload GroupInfo