【问题标题】:Uploading Image byte array with httpurlconnection and android使用 httpurlconnection 和 android 上传图像字节数组
【发布时间】:2013-03-10 22:00:48
【问题描述】:

我正在开发小型 android 应用程序,我想在其中将图像从我的 android 设备上传到我的服务器。我为此使用HttpURLConnection

我这样做是通过以下方式:

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_float);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);

byte[] data = bos.toByteArray();

connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "image/jpeg");
connection.setRequestMethod(method.toString());

ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
bout.write(data); 
bout.close();

我正在使用ByteArrayOutputStream,但我不知道如何使用我的 httpurlconnection 传递该数据。这是传递原始图像数据的正确方法吗?我只是想发送包含图像数据的字节数组。没有转换或没有多部分发送。 我的代码工作正常,没有任何错误,但我的服务器给了我回复 {"error":"Mimetype not supported: inode\/x-empty"}

我使用setEntity 使用httpclient 完成了此操作,并且可以正常工作。但我想使用 urlconnection。

我做错了吗?这个怎么做? 谢谢。

【问题讨论】:

  • 我想按原样发送此字节数组,而不将其转换为字符串或多部分任何解决方案。就像在 httpclient 中我做了这个client.setEntity(new ByteArrayEntity(data)); 有没有办法在 urlconnection 中做类似的事情。需要帮忙。谢谢。

标签: android mime-types content-type httpurlconnection


【解决方案1】:
private void doFileUpload(){

          HttpURLConnection conn = null;
          DataOutputStream dos = null;
          DataInputStream inStream = null; 


          String exsistingFileName = "/sdcard/six.3gp";
          // Is this the place are you doing something wrong.

          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary =  "*****";


          int bytesRead, bytesAvailable, bufferSize;

          byte[] buffer;

          int maxBufferSize = 1*1024*1024;

          String urlString = "http://192.168.1.5/upload.php";



          try
          {


          Log.e("MediaPlayer","Inside second Method");

          FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );



           URL url = new URL(urlString);

           conn = (HttpURLConnection) url.openConnection();

           conn.setDoInput(true);

           // Allow Outputs
           conn.setDoOutput(true);

           // Don't use a cached copy.
           conn.setUseCaches(false);

           // Use a post method.
           conn.setRequestMethod("POST");

           conn.setRequestProperty("Connection", "Keep-Alive");

           conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);


           dos = new DataOutputStream( conn.getOutputStream() );

           dos.writeBytes(twoHyphens + boundary + lineEnd);
           dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
           dos.writeBytes(lineEnd);

           Log.e("MediaPlayer","Headers are written");



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

           BufferedReader in = new BufferedReader(
                           new InputStreamReader(
                           conn.getInputStream()));
                String inputLine;

                while ((inputLine = in.readLine()) != null) 
                    tv.append(inputLine);




           // close streams
           Log.e("MediaPlayer","File is written");
           fileInputStream.close();
           dos.flush();
           dos.close();


          }
          catch (MalformedURLException ex)
          {
               Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
          }

          catch (IOException ioe)
          {
               Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
          }


          //------------------ read the SERVER RESPONSE


          try {
                inStream = new DataInputStream ( conn.getInputStream() );
                String str;

                while (( str = inStream.readLine()) != null)
                {
                     Log.e("MediaPlayer","Server Response"+str);
                }
                /*while((str = inStream.readLine()) !=null ){

                }*/
                inStream.close();

          }
          catch (IOException ioex){
               Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
          }



        }

Complete Demo

【讨论】:

  • 嗨 Nirav 感谢您的重播。其实我不想使用多部分。我只想在请求正文中发送原始图像字节数组。因为我的服务器端不处理图像的多部分。所以我只想发送字节数组。您的解决方案是否可以帮助我做到这一点?需要帮忙。谢谢。
  • @nirav,此代码运行良好,但如何将文件名也作为参数添加到图像文件中?
【解决方案2】:

您必须打开输出流连接并将数据写入其中。 你可以试试这个:

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_float);

connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "image/jpeg");
connection.setRequestMethod(method.toString());
OutputStream outputStream = connection.getOutputStream();

ByteArrayOutputStream bos = new ByteArrayOutputStream(outputStream);
bitmap.compress(CompressFormat.JPEG, 100, bos);

bout.close();
outputStream.close();

有了这个声明:

bitmap.compress(CompressFormat.JPEG, 100, bos);

您正在做两件事:压缩位图并将结果数据(构建 jpg 的字节)发送到 bos 流,然后将结果数据发送到输出流连接。

也可以直接在连接的输出流中写入数据,替换为:

ByteArrayOutputStream bos = new ByteArrayOutputStream(outputStream);
bitmap.compress(CompressFormat.JPEG, 100, bos);

有了这个:

bitmap.compress(CompressFormat.JPEG, 100, outputStream);

我希望这可以帮助您了解 HttpUrlConnection 的工作原理。

此外,您不应完全加载整个位图以避免“内存不足”异常,例如使用流打开位图。

【讨论】:

    【解决方案3】:
     HttpParams httpParameters = new BasicHttpParams();
                    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
                    HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
                    HttpClient httpclient = new DefaultHttpClient(httpParameters);
                    HttpPost httppost = new HttpPost(ServerConstants.urll);
                    httppost.setHeader("Content-type","application/octet-stream");//application/octet-stream    
    
                // the below is the important one, notice no multipart here just the raw image data 
                httppost.setEntity(new ByteArrayEntity(imagebytess));               
    
    
                try {
                    HttpResponse res = httpclient.execute(httppost);                
    
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            res.getEntity().getContent(), "UTF-8"));
                    String sResponse;
                    StringBuilder s = new StringBuilder();
                    System.out.println("Response: " + res.getStatusLine().getStatusCode());
                    while ((sResponse = reader.readLine()) != null) {
                        s = s.append(sResponse);
                        System.out.println("Response: " + res.getStatusLine().getStatusCode());
                    }`enter code here`
                    System.out.println("Response: " + s.toString());
                } catch `enter code here`(ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-22
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 2017-09-30
      相关资源
      最近更新 更多