使用httpurlconnection和android上传Image字节数组

时间:2013-03-21 11:52:32

标签: android mime-types content-type httpurlconnection

我正在开发小型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。

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

1 个答案:

答案 0 :(得分:3)

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