Android从摄像头上传图像导致应用程序崩溃

Android从摄像头上传图像导致应用程序崩溃,android,Android,我正在尝试从gallery和camera上传图像。上传gallery图像非常有效,但在尝试从具有http 400状态的camera上传图像时崩溃 //打开意图的方法 private void openImageIntent() { // Determine Uri of camera image to save. final File root = new File(Environment.getExternalStorageDirectory() + File.separat

我正在尝试从gallery和camera上传图像。上传gallery图像非常有效,但在尝试从具有http 400状态的camera上传图像时崩溃 //打开意图的方法

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);
}
//上载文件的方法

 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();
}

我添加了文件扩展名,效果很好

在第一个函数中,我替换了==>最后一个字符串fname=“thisFile”;
最后一个字符串为fname=“thisFile.jpg”

@theUturn还应确保您已定义了所有使用权限。
 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();
}
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) {


}
}
/**
 * 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;
}



}
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)