2016-03-26 25 views
0

1つのアプリを開発します。私のアプリでは、カメラから1枚、ギャラリーから1枚の画像を撮影します。私はMultipartを使用してイメージをサーバーにポストしますが、イメージはポストしません。私のポストデータは、私のJavaコードがマルチパートを使用してデータを投稿するには?

public void onActivityResult(int requestCode, int resultCode, Intent data) { 

if (requestCode == PICK_FROM_CAMERA) { 
    try{ 
     if(resultCode == -1){ 
      File file = new File(Environment.getExternalStorageDirectory()+File.separator +"image.png"); 
      bitmap = loadBitmap(file); 
      iv_pic.setImageBitmap(bitmap); 

     try { 
      Uri tempUri = getImageUri(getActivity(), bitmap); 
      Log.i(TAG,"onActivityResult PICK_FROM_CAMERA, tempUri : "+tempUri); 

     //uploadFile(tempUri + "" + System.currentTimeMillis()+".png"); 
     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
     }else{ 
     //setResult(RESULT_CANCELED); 
     //Activity.this.finish(); 
     } 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
}else if (requestCode == PICK_FROM_GALLERY) { 
     try{ 
      //Log.i(TAG,"onActivityResult PICK_FROM_GALLERY, data : "+data); 
      if(data !=null){ 
       bitmap = null; 
       try { 
        bitmap = new BitmapDrawable(MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData())).getBitmap(); 
        iv_pic.setImageBitmap(bitmap); 

        try { 
         Uri tempUri = getImageUri(getActivity(), bitmap); 
         Log.i(TAG,"onActivityResult PICK_FROM_GALLERY, tempUri : "+tempUri); 

         //uploadFile(tempUri + "" + System.currentTimeMillis()+".png"); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 

       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      }else{ 
       //setResult(RESULT_CANCELED); 
       //Activity.this.finish(); 
      } 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 

public Uri getImageUri(Context context , Bitmap bitmap) { 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    bitmap.compress(Bitmap.CompressFormat.JPEG , 100 , bytes); 
    String path = Images.Media.insertImage(context.getContentResolver() , bitmap , "Title" , null); 
    return Uri.parse(path); 
} 

ある

{ 
    "suggested_item" :{ 
     "name": "apple", 
     "description" : "nice apple", 
     "image": "image.png" 
    } 
    } 

を下回っている私に事前に感謝を助けてください。

+0

イメージをサーバーにアップロードしますか? –

+0

はい、上記は私のpostdataです.....私は名前と説明を掲載していますが、画像に問題があります。これは私のコードです... JSONObject jsonObj = new JSONObject(); \t \t \t \t \t JSONObject child_obj = new JSONObject(); \t \t \t \t \t child_obj.put( "name"、name); \t \t \t \t \t child_obj.put( "description"、description); \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t //child_obj.put("image」、画像) \t \t \t \t \t jsonObj.put( "suggested_item"、child_obj); ......私はマルチパートフォームデータで画像を送信したいと思います。 – Shailesh

答えて

0

バイナリデータを送信するには、MultipartEntityBuilderのaddBinaryBodyメソッドを使用する必要があります。添付のサンプル:次に

import org.apache.http.entity.ContentType; 
import org.apache.http.entity.mime.MultipartEntityBuilder; 
//Image attaching 
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); 
File file; 
multipartEntity.addBinaryBody("someName", file, ContentType.create("image/jpeg"), file.getName()); 
//Json string attaching 
String json; 
multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN)); 

いつものように要求します:

HttpPut put = new HttpPut("url"); 
put.setEntity(multipartEntity.build()); 
HttpResponse response = client.execute(put); 
int statusCode = response.getStatusLine().getStatusCode(); 
0

私はretrofitを使用してお勧めします。

ポスティングマルチパートは次のようなものになります。

@Multipart 
@PUT("user/photo") 
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description); 

詳細については、このquestionを参照してください。

Thisは、改造に精通していないかどうかを確認する良いチュートリアルです。ここで

0

私が理解するためにも、サーバーのPHPコード上でHTTPを使用して画像をアップロードのための完全なコードを投稿しています、

クラスファイル

package com.stackexmples; 

import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.AppCompatButton; 
import android.util.Log; 
import android.view.View; 
import android.widget.LinearLayout; 
import android.widget.TextView; 

import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

/** 
* Created by windws on 26-Mar-16. 
*/ 
public class UploadImage extends AppCompatActivity implements View.OnClickListener { 
    private static final int REQUEST_TAKE_GALLERY_VIDEO = 11; 
    private static final String TAG = "UploadMultipleFile"; 
    private AppCompatButton btnUploadFiles; 
    private AppCompatButton bntSelectImage; 
    private String filemanagerstring; 
    private String selectedImagePath=""; 
    private TextView tvVideoList; 
    private TextView tvImageList; 
    private int selected = 0; 
    private LinearLayout ll; 
    private int count = 0; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_upload_multiple_file); 
     initView(); 
     initListener(); 

    } 

    private void initView() { 
     btnUploadFiles = (AppCompatButton) findViewById(R.id.btnUploadFiles); 
     bntSelectImage = (AppCompatButton) findViewById(R.id.bntSelectImage); 
    } 

    private void initListener() { 
     btnUploadFiles.setOnClickListener(this); 
     bntSelectImage.setOnClickListener(this); 
    } 


    @Override 
    public void onClick(View v) { 
     if (v == btnUploadFiles) { 
      Thread thread = new Thread(new Runnable() { 
       @Override 
       public void run() { 
        uploadFile("Data you want to sent"); 
       } 
      }); 
      thread.start(); 
     } else if (v == bntSelectImage) { 
      selectImage(); 
     } 
    } 

    private void selectImage() { 
     selected = 1; 
     Intent intent = new Intent(); 
     intent.setType("Image/*"); 
     intent.setAction(Intent.ACTION_GET_CONTENT); 
     startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_TAKE_GALLERY_VIDEO); 
    } 


    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode == RESULT_OK) { 

      if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) { 
       Log.d(TAG, "Called-->onActivityResultCalled"); 
       Uri selectedImageUri = data.getData(); 
       Log.d(TAG, "selectedImageUri-->" + selectedImageUri); 
       selectedImagePath = selectedImageUri.toString().replace("file://", ""); 
      } 
     } 
     super.onActivityResult(requestCode, resultCode, data); 
    } 

    public String uploadFile(String req) { 
     // TODO Auto-generated method stub 
     String serverResponseMessage = ""; 
     String response_return = ""; 
     Log.d("first str is:", req); 
     String urlString = "http://192.168.1.32/TestUpload/upload.php"; 
     URL imageUrl = null; 
     try { 
      imageUrl = new URL(urlString); // get WebService_URL 
     } catch (MalformedURLException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 
     // generating byte[] boundary here 

     HttpURLConnection conn = null; 
     DataOutputStream outputStream = null; 

     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 10 * 1024 * 1024; 

     try { 
      int serverResponseCode; 
      conn = (HttpURLConnection) imageUrl.openConnection(); 
      conn.setConnectTimeout(10000); 
      conn.setReadTimeout(10000); 
      conn.setDoOutput(true); 
      conn.setDoInput(true); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Connection", "Keep-Alive"); 
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
      outputStream = new DataOutputStream(conn.getOutputStream()); 

      ////////////////////////////////////////////////////// 
      outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
      outputStream.writeBytes("Content-Disposition: form-data; name=\"json\"" + lineEnd); 
      outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd); 
      outputStream.writeBytes("Content-Length: " + req.length() + lineEnd); 
      outputStream.writeBytes(lineEnd); 
      outputStream.writeBytes(req + lineEnd); 
      outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
      try { 
       FileInputStream fileInputStream = new FileInputStream(selectedImagePath); 
       String lastOne = "temp"; 
       ///////////////////////////////////////////// 
       outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
       outputStream.writeBytes("Content-Disposition: attachment; name=\"imageKey" + "\";" + " filename=" + lastOne +".jpg" + lineEnd); // pass key & value of photo 
        /*outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);*/ 
       outputStream.writeBytes(lineEnd); 
       bytesAvailable = fileInputStream.available(); // photo size bytes 
       bufferSize = Math.min(bytesAvailable, maxBufferSize); 
       buffer = new byte[bufferSize]; 
       // Read file 
       bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
       while (bytesRead > 0) { 
        outputStream.write(buffer, 0, bufferSize); 
        bytesAvailable = fileInputStream.available(); 
        bufferSize = Math.min(bytesAvailable, maxBufferSize); 
        bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
       } 
       outputStream.writeBytes(lineEnd); 
       Log.d("posttemplate", "connection outputstream size is " + outputStream.size()); 
       fileInputStream.close(); 
      } catch (OutOfMemoryError o) { 
      } 
      outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
      serverResponseCode = conn.getResponseCode(); 
      serverResponseMessage = conn.getResponseMessage(); 
      InputStream is = conn.getInputStream(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
      String line; 
      StringBuffer response1 = new StringBuffer(); 
      while ((line = rd.readLine()) != null) { 
       response1.append(line); 
       response1.append('\r'); 
      } 
      rd.close(); 
      response_return = response1.toString(); 

      Log.d("posttemplate", "server response code " + serverResponseCode); 
      Log.d("posttemplate", "server response message " 
        + serverResponseMessage); 
      outputStream.flush(); 
      outputStream.close(); 
      conn.disconnect(); 

     } catch (MalformedURLException e) { 
      Log.d("posttemplate", "malformed url", e); 
     } catch (IOException e) { 
      Log.d("posttemplate", "ioexception", e); 
     } 
     Log.d("response--->", "****" + response_return); 
     return response_return; 
    } 
} 

レイアウトファイル

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.materialexample.UploadMultipleFile.UploadMultipleFile"> 
    <android.support.v7.widget.AppCompatButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/btnUploadFiles" 
     android:text="Upload Files" /> 
    <LinearLayout 
     android:id="@+id/linearLayout1" 
     android:orientation="vertical" 
     android:layout_below="@id/btnUploadFiles" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <android.support.v7.widget.AppCompatButton 
      android:id="@+id/bntSelectImage" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Select Image" /> 

    </LinearLayout> 



</RelativeLayout> 

PHPコード

を理解するために
<?php 
$file_path = "uploads/"; 

    $file_path = $file_path . basename($_FILES['imageKey']['name']); 
    if(move_uploaded_file($_FILES['imageKey']['tmp_name'], $file_path)) { 
     echo "success"; 
    } else{ 
     echo "fail"; 
    } 
if(isset($_REQUEST['json'])){ 
    echo "text is-->".$_REQUEST['json']; 
} 

?> 
関連する問題