2016-04-07 9 views
0

Ich versuche Bild aus der Galerie und Kamera hochzuladen Galeriebildes für das Hochladen, aber Abstürze perfekt funktioniert, während Bild von der Kamera mit http 400 Status // Methode zum Hochladen von Tring Absicht zu öffnenAndroid-Upload Bild von der Kamera gibt Abstürze Anwendung

private void openImageIntent() { 

    // Determine Uri of camera image to save. 
    final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator); 
    root.mkdirs(); 
    final String fname = "thisFile"; 
    final File sdImageMainDirectory = new File(root, fname); 
    outputFileUri = Uri.fromFile(sdImageMainDirectory); 

    // Camera. 
    final List<Intent> cameraIntents = new ArrayList<Intent>(); 
    final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
    final PackageManager packageManager = getPackageManager(); 
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0); 
    for(ResolveInfo res : listCam) { 
     final String packageName = res.activityInfo.packageName; 
     final Intent intent = new Intent(captureIntent); 
     intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); 
     intent.setPackage(packageName); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 
     cameraIntents.add(intent); 
    } 

    // Filesystem. 
    final Intent galleryIntent = new Intent(); 
    galleryIntent.setType("image/* video/*"); 
    galleryIntent.setAction(Intent.ACTION_PICK); 

    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source"); 

    // Add the camera options. 
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()])); 

    startActivityForResult(chooserIntent, 1); 
} 

// onActivity Ergebnis Methode

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == RESULT_OK) { 
     if (requestCode == 1) { 
      final boolean isCamera; 
      if (data == null) { 
       isCamera = true; 
      } else { 
       final String action = data.getAction(); 
       if (action == null) { 
        isCamera = false; 
       } else { 
        isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       } 
      } 


      if (isCamera) { 

       selectedImageUri = outputFileUri; 
       // Toast.makeText(UpdateProfileActivity.this,selectedImageUri+"",Toast.LENGTH_SHORT).show(); 
       System.out.println("-------camera---------------------"+selectedImageUri); 

       File myFile = new File(selectedImageUri.getPath()); 
       myFile.getAbsolutePath(); 
       this.file_path= myFile.getAbsolutePath(); 
       System.out.println("-------file_path---------------------"+file_path); 
       uploadFile(); 
      } else { 
       selectedImageUri = data == null ? null : data.getData(); 
       // Toast.makeText(LiveChatActivity.this,selectedImageUri+"",Toast.LENGTH_SHORT).show(); 
       Uri selectedImage = data.getData(); 
       String[] filePathColumn = {MediaStore.Images.Media.DATA}; 

       Cursor cursor = getContentResolver().query(
         selectedImage, filePathColumn, null, null, null); 
       cursor.moveToFirst(); 

       int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
       String filePath = cursor.getString(columnIndex); 
       this.file_path=filePath; 

       uploadFile(); 
      } 
     } 

    } 
} 

// Methodendatei

public void uploadFile(){ 
    SharedPreferences sf = LiveChatActivity.this.getSharedPreferences("all", 0); 

    String reqUrl = ApiUrls.getEventDetails + "/comments";  
    HashMap<String, String> formValues = new HashMap<>(); 
    formValues.put("comment_post_ID", event_id); 
    formValues.put("comment_author", "ves");//sf.getString("display_name", "comment_author") 
    formValues.put("comment_author_email", sf.getString("user_email", "user_email")); 
    formValues.put("comment_content", comment_content); 
    formValues.put("user_id", sf.getString("user_id", "user_id")); 
    formValues.put("file", this.file_path); 
    HashMap<String, String> fileValues = new HashMap<String, String>(); 
    fileValues.put("file", this.file_path); 
    WebServiceUtil wUtil = new WebServiceUtil(LiveChatActivity.this, reqUrl, formValues, true, fileValues); 
    wUtil.execute(); 
} 
hochladen Dienstprogramm

webservice.java von How to put HTTP multipart request body together in order to send some string parameters along with image

public class WebServiceUtil extends AsyncTask<String, Integer, String> { 

HashMap<String, String> formValues; 
HashMap<String, String> fileValues; 

Boolean uploadFile; 
String reqUrl; 
String result; 
ProgressDialog dialog; 
Context context; 

public WebServiceUtil(Context context, String reqUrl, 
         HashMap<String, String> formValues, Boolean uploadFile, 
         HashMap<String, String> fileValues) { 

    this.context = context; 
    this.reqUrl = reqUrl; 
    this.formValues = formValues; 

    this.uploadFile = uploadFile; 
    if (uploadFile) { 

     this.fileValues = fileValues; 
    } 
} 

@Override 
protected void onPreExecute() { 

    super.onPreExecute(); 

} 

// 

@Override 
protected String doInBackground(String... URLs) { 

    List<String> response = null; 
    try { 
     MultipartUtility mu = new MultipartUtility(context, reqUrl, "UTF-8"); 

     for (Map.Entry<String, String> entry : formValues.entrySet()) { 
      String key = entry.getKey(); 

      String value = entry.getValue(); 

      mu.addFormField(key, value); 

     } 

     if (uploadFile) { 


      for (Map.Entry<String, String> entry : fileValues.entrySet()) { 
       String key = entry.getKey(); 

       String value = entry.getValue(); 


       File file =new File(value); 
       mu.addFilePart(key, file); 

      } 

     } 

     response = mu.finish(); 

    } catch (IOException e) { 

     e.printStackTrace(); 
    } 

    return response.toString(); 

} 

protected void onPostExecute(String result) { 


} 
} 

MultipartUtility.java angepasst von codejava.net

/** 
* This utility class provides an abstraction layer for sending multipart HTTP 
* POST requests to a web server. 
* @author www.codejava.net 
* 
*/ 
public class MultipartUtility { 
private final String boundary; 
private static final String LINE_FEED = "\r\n"; 
private HttpURLConnection httpConn; 
private String charset; 
private OutputStream outputStream; 
private PrintWriter writer; 
ProgressDialog dialog; 

/** 
* This constructor initializes a new HTTP POST request with content type 
* is set to multipart/form-data 
* @param requestURL 
* @param charset 
* @throws IOException 
*/ 
public MultipartUtility(Context context,String requestURL, String charset) 
     throws IOException { 
    //dialog = new ProgressDialog(context); 
    this.charset = charset; 

    // creates a unique boundary based on time stamp 
    boundary = "===" + System.currentTimeMillis() + "==="; 

    URL url = new URL(requestURL); 
    httpConn = (HttpURLConnection) url.openConnection(); 
    httpConn.setUseCaches(false); 
    httpConn.setDoOutput(true); // indicates POST method 
    httpConn.setDoInput(true); 
    SharedPreferences sf=context.getSharedPreferences("all", 0); 
    String authToken=sf.getString("authToken",""); 

    httpConn.setRequestProperty("authToken", authToken); 
    httpConn.setRequestProperty("Content-Type", 
      "multipart/form-data; boundary=" + boundary); 
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); 
    httpConn.setRequestProperty("Test", "Bonjour"); 
    outputStream = httpConn.getOutputStream(); 
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), 
      true); 
} 

/** 
* Adds a form field to the request 
* @param name field name 
* @param value field value 
*/ 
public void addFormField(String name, String value) { 
    writer.append("--" + boundary).append(LINE_FEED); 
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"") 
      .append(LINE_FEED); 
    writer.append("Content-Type: text/plain; charset=" + charset).append(
      LINE_FEED); 
    writer.append(LINE_FEED); 
    writer.append(value).append(LINE_FEED); 
    writer.flush(); 
} 

/** 
* Adds a upload file section to the request 
* @param fieldName name attribute in <input type="file" name="..." /> 
* @param uploadFile a File to be uploaded 
* @throws IOException 
*/ 
public void addFilePart(String fieldName, File uploadFile) 
     throws IOException { 
    String fileName = uploadFile.getName(); 
    writer.append("--" + boundary).append(LINE_FEED); 
    writer.append(
      "Content-Disposition: form-data; name=\"" + fieldName 
        + "\"; filename=\"" + fileName + "\"") 
      .append(LINE_FEED); 
    writer.append(
      "Content-Type: " 
        + URLConnection.guessContentTypeFromName(fileName)) 
      .append(LINE_FEED); 
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); 
    writer.append(LINE_FEED); 
    writer.flush(); 

    FileInputStream inputStream = new FileInputStream(uploadFile); 
    byte[] buffer = new byte[4096]; 
    int bytesRead = -1; 
    while ((bytesRead = inputStream.read(buffer)) != -1) { 
     outputStream.write(buffer, 0, bytesRead); 
    } 
    outputStream.flush(); 
    inputStream.close(); 

    writer.append(LINE_FEED); 
    writer.flush(); 
} 

/** 
* Adds a header field to the request. 
* @param name - name of the header field 
* @param value - value of the header field 
*/ 
public void addHeaderField(String name, String value) { 
    writer.append(name + ": " + value).append(LINE_FEED); 
    writer.flush(); 
} 

/** 
* Completes the request and receives response from the server. 
* @return a list of Strings as response in case the server returned 
* status OK, otherwise an exception is thrown. 
* @throws IOException 
*/ 
public List<String> finish() throws IOException { 


    List<String> response = new ArrayList<String>(); 

    writer.append(LINE_FEED).flush(); 
    writer.append("--" + boundary + "--").append(LINE_FEED); 
    writer.close(); 

    // checks server's status code first 
    int status = httpConn.getResponseCode(); 
    if (status == HttpURLConnection.HTTP_OK) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       httpConn.getInputStream())); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      response.add(line); 
     } 
     reader.close(); 
     httpConn.disconnect(); 
    } else { 
     throw new IOException("Server returned non-OK status: " + status); 
    } 


    return response; 
} 



} 

// Crashlog

04-07 10:19:51.069 32014-32157/eaglevision.tellmeelive W/System.err: java.io.IOException: Server returned non-OK status: 400 
04-07 10:19:51.079 32014-32157/eaglevision.tellmeelive W/System.err:  at eaglevision.tellmeelive.api.MultipartUtility.finish(MultipartUtility.java:165) 
04-07 10:19:51.079 32014-32157/eaglevision.tellmeelive W/System.err:  at eaglevision.tellmeelive.api.WebServiceUtil.doInBackground(WebServiceUtil.java:89) 
04-07 10:19:51.079 32014-32157/eaglevision.tellmeelive W/System.err:  at eaglevision.tellmeelive.api.WebServiceUtil.doInBackground(WebServiceUtil.java:22) 
04-07 10:19:51.079 32014-32157/eaglevision.tellmeelive W/System.err:  at android.os.AsyncTask$2.call(AsyncTask.java:292) 
04-07 10:19:51.079 32014-32157/eaglevision.tellmeelive W/System.err:  at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
04-07 10:19:51.079 32014-32157/eaglevision.tellmeelive W/System.err:  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
04-07 10:19:51.079 32014-32157/eaglevision.tellmeelive W/System.err:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
04-07 10:19:51.079 32014-32157/eaglevision.tellmeelive W/System.err:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
04-07 10:19:51.079 32014-32157/eaglevision.tellmeelive W/System.err:  at java.lang.Thread.run(Thread.java:818) 
+0

Veröffentlichen Sie Ihr Absturzprotokoll – Jas

+0

@theUturn Stellen Sie außerdem sicher, dass Sie alle Verwendungen-Berechtigungen definiert haben. –

+0

theUturn

Antwort

0

I Dateierweiterung hinzugefügt und es funktionierte

in der ersten Funktion, die ich ersetzte ===> final String fname = "thisFile"; mit endgültigem String fname = "thisFile.jpg";

Verwandte Themen