【问题标题】:how to upload image using byte array如何使用字节数组上传图像
【发布时间】:2017-01-18 06:18:36
【问题描述】:

我正在尝试使用此代码上传图片:

   private String uploadFile() {
 String responseString = null;

 try {

  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL_M);



  Log.i("UploadApp", "upload url: " + Config.FILE_UPLOAD_URL_M);


  AndroidMultiPartEntity entity;
  entity = new AndroidMultiPartEntity(
   new AndroidMultiPartEntity.ProgressListener() {

    @Override
    public void transferred(long num) {
     // publishProgress((int) ((num / (float) totalSize) * 100));
    }
   });

  File sourceFile;
  sourceFile = new File(compressImage(filePath));

  Log.i("UploadApp", "file path: " + filePath);

  // Adding file data to http body

  entity.addPart("f", new FileBody(sourceFile)); //problem is here


  entity.addPart("category", new StringBody("Bill"));
  entity.addPart("description", new StringBody("test single"));
  entity.addPart("file", new StringBody("unknown1"));
  entity.addPart("clientid", new StringBody("4"));



  totalSize = entity.getContentLength();
  httppost.setEntity(entity);

  // Making server call
  HttpResponse response = httpclient.execute(httppost);
  HttpEntity r_entity = response.getEntity();

  int statusCode = response.getStatusLine().getStatusCode();
  if (statusCode == 200) {
   // Server response
   responseString = EntityUtils.toString(r_entity);
  } else {
   responseString = "Error occurred! Http Status Code: " + statusCode;
  }

 } catch (ClientProtocolException e) {
  responseString = e.toString();
  Log.e("UploadApp", "exception: " + responseString);
 } catch (IOException e) {
  responseString = e.toString();
  Log.e("UploadApp", "exception: " + responseString);
 }

 return responseString;

}

我有一个上传图片的网络服务,它有 5 个参数,其中 4 个是字符串,一个是字节数组 (byte[] f)

主要问题:如何将我的源文件(图像)转换为字节数组,以将图像上传到服务器上,上面的代码对应于这个网络服务。

【问题讨论】:

  • 您的代码已经将文件作为字节数组上传。正常的分段上传就是这样做的。

标签: android arrays android-asynctask http-post android-image


【解决方案1】:

您可以使用android第三方“AndroidAsync”。您可以通过此代码执行任何操作。请检查此

https://github.com/koush/AndroidAsync

谢谢

【讨论】:

    【解决方案2】:

    首先,你可以从源文件中获取绝对路径,然后调用上传方法

    String mCurrentPhotoPath = sourceFile.getAbsolutePath();
    
    
    private String upload() {
            Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 50, bao);
            byte[] ba = bao.toByteArray();
            return Base64.encodeToString(ba, Base64.DEFAULT);
    
        }
    

    【讨论】:

    • 如何在这里调用你的方法:entity.addPart("f", new FileBody(sourceFile));?
    【解决方案3】:

    您可以使用此代码上传任何文件,仅发送带有点扩展名文件编码字符串的文件名

    在服务器端发送编码字符串和Base64.decode文件字符串

    String strAttachmentCoded = "";
    private int PICK_PDF_REQUEST = 1;
    Uri filePath;
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == PICK_PDF_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            File uploadFile = new File(filePath.toString());
            URI uri = URI.create(uploadFile.getPath());
            try {
                if (uploadFile != null) {
                    File uploadFile1 = new File(uri);
                    FileInputStream objFileIS = new FileInputStream(uploadFile1);
                    ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
                    byte[] byteBufferString = new byte[1024];
                    int readNum;
                    readNum = objFileIS.read(byteBufferString);
                    while (readNum != -1) {
                        Log.v("  ", "" + readNum);
                        objByteArrayOS.write(byteBufferString, 0, readNum);
                        //                system.out.println("read " + readNum + " bytes,");
                        readNum = objFileIS.read(byteBufferString);
                    }
                    byte[] byteBinaryData = Base64.encode(objByteArrayOS.toByteArray(), Base64.DEFAULT);
                    strAttachmentCoded = String.valueOf(byteBinaryData);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 2016-08-22
      • 2020-10-30
      • 2017-01-17
      • 2011-09-09
      • 1970-01-01
      • 2020-01-22
      • 2021-03-25
      • 2018-08-01
      相关资源
      最近更新 更多