3

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

我使用 httpclient 做到了这一点,setEntity并且它可以正常工作。但我想使用 urlconnection。

难道我做错了什么?这个怎么做?谢谢你。

4

3 回答 3

5

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.

于 2013-03-29T01:21:49.637 回答
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);
          }



        }

完整演示

于 2013-03-21T11:55:20.243 回答
0
 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();
            }
于 2015-09-10T13:13:28.150 回答