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

出力ストリーム接続を開き、そこにデータを書き込む必要があります。これを試すことができます:

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 の仕組みを理解するのに役立つことを願っています。

また、「メモリ不足」の例外を回避するために、ビットマップ全体を完全にロードしないでください。たとえば、ストリームでビットマップを開きます。

于 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 に答える