Uploading Image byte array with httpurlconnection

2019-03-21 16:42发布

问题:

I am developing small android application in which I wanted to upload image from my android device to my server. I am using HttpURLConnection for that.

I am doing this in following way:

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

I am using ByteArrayOutputStream but I don't know how to pass that data with my httpurlconnection. Is this the correct way to pass raw image data. I just wanted to send byte array which contains image data. No conversion or no multipart sending. My code working fine without any error but it my server gives me reply {"error":"Mimetype not supported: inode\/x-empty"}

I did this with httpclient using setEntity and its working fine with that. But I want to use urlconnection.

Am I doing something wrong? How to do this? Thank you.

回答1:

You must open the output stream connection and write the data in it. You could try this:

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

With this statement:

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

You are doing two things: compress the bitmap and send the resulted data (the bytes that build the jpg) to bos stream, that send the resulted data to the output stream connection.

Also you can write the data in the output stream of the connection directly, replacing this:

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

With this:

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

I hope this helps you understand how HttpUrlConnection works.

Also, you should not load the whole bitmap entirely for avoid the "out of memory" exceptions, opening the bitmap with streams, for example.



回答2:

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



回答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();
            }