Android相机上传捕获的图像出现问题

3
在我的应用程序中,我正在尝试从我的设备捕获图像,并且我想将其上传到服务器。我正在遵循此答案的步骤:here 以下是启动相机的代码:
 startBtn = (Button) findViewById(R.id.startBtn);
 startBtn.setOnClickListener(new View.OnClickListener() 
  {
    public void onClick(View v) 
       {
            startCamera();
        }
    });
}

public void startCamera() 
{        
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
    intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
    startActivityForResult( intent, 0 );
}

但是当我捕获后,尝试上传时它会崩溃。在logcat中显示错误在OnActivityResultdoFileUpload中。

以下是我的代码:

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {   
        switch( resultCode )
        {
            case 0:
                break;

            case -1:
                onPhotoTaken();
                break;
        }
    }

    protected void onPhotoTaken()
    {
        doFileUpload(MediaStore.EXTRA_OUTPUT);
    }

    private void doFileUpload(String extraOutput)
    {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inStream = null;        
        String urlServer = "http:XXXXXXXXXXXXXXXXXXXXXX/upload.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        FileInputStream fileInputStream = new FileInputStream(new File(extraOutput) );
        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
        outputStream = new
        DataOutputStream( connection.getOutputStream() );
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"userfile\";filename=\"" + extraOutput +"\"" + lineEnd);
        outputStream.writeBytes(lineEnd);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        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);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens +lineEnd);
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();       
        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
     }

请帮我修复我的错误......拜托


你必须更具体一些。LogCat中显示的是什么类型的错误? - Alexander Stolz
除此之外:您不应该在UI线程中进行网络操作,这是绝对不可以的。 - Alexander Stolz
@Siva K :你能给我完整的代码吗? - Nirav Ranpara
@Nirav Ranpara - 你有什么问题,可以给我发邮件(sivasankarkb@gmail.com),我会帮助你的。 - Siva K
@Nirav Ranpara - 抱歉回复晚了... - Siva K
@SivaK:请把我加入你的 Gmail 联系人中,我会发送请求。 - Nirav Ranpara
1个回答

3
我正在使用这段代码将我的设备上的图像上传到服务器。
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.v("Test", "IGA");
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            selectedImageUri =(Uri)data.getData();
            AddCourtActivity.mImage.setImageURI(selectedImageUri);
            selectedImagePath = getPath(selectedImageUri);
            imagePath=selectedImagePath;
            Log.v("Test","IGA "+imagePath);
        } else if (requestCode == CAMERA_PIC_REQUEST) {

            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            imagePath=selectedImagePath;

            Log.v("Test","IGA1 "+imagePath);
            AddCourtActivity.mImage.setImageBitmap(thumbnail);
        }
    }
    if (resultCode == RESULT_CANCELED) {

        return;
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
public String getPath1(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow("userImage"/*MediaStore.Images.Media.DATA*/);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
}

//Use this class for upload image to server


public class FileUploader {

private String Tag = "UPLOADER";
private String urlString;// = "YOUR_ONLINE_PHP";
HttpURLConnection conn;
String exsistingFileName;
public String result;

public String uploadImageData(String serverImageTag) {// Server image tag
                                                        // may be
                                                        // courtImage[] or
                                                        // userImage
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    try {
        // ------------------ CLIENT REQUEST

        Log.e(Tag, "Inside second Method");

        FileInputStream fileInputStream = new FileInputStream(new File(
                exsistingFileName));

        // open a URL connection to the Servlet

        URL url = new URL(urlString);

        // Open a HTTP connection to the URL

        conn = (HttpURLConnection) url.openConnection();

        // Allow Inputs
        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);

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        if (serverImageTag.equalsIgnoreCase("courtImage")) {
            dos.writeBytes("Content-Disposition: post-data; name=courtImage[];filename="
                    + exsistingFileName + "" + lineEnd);
        } else if (serverImageTag.equalsIgnoreCase("userImage")) {
            dos.writeBytes("Content-Disposition: post-data; name=userImage[];filename="
                    + exsistingFileName + "" + lineEnd);
        }
        dos.writeBytes(lineEnd);

        Log.e(Tag, "Headers are written");

        // create a buffer of maximum size

        int bytesAvailable = fileInputStream.available();
        int maxBufferSize = 1000;
        // int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bytesAvailable];

        // read file and write it into form...

        int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bytesAvailable);
            bytesAvailable = fileInputStream.available();
            bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
        }

        // send multipart form data necessary after file data...

        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        String serverResponseMessage = conn.getResponseMessage();
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));

        // String serverResponseCode = conn.
        // String serverResponseMessage = conn.getResponseMessage();

        while ((result = rd.readLine()) != null) {

            Log.v("result", "result " + result);

                Login.fbResponse = result;

        }
        // close streams
        Log.e(Tag, "File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
        rd.close();
    } catch (MalformedURLException ex) {
        Log.e(Tag, "error: " + ex.getMessage(), ex);
    }

    catch (IOException ioe) {
        Log.e(Tag, "error: " + ioe.getMessage(), ioe);
    }

    // Parsing has finished.
    return result;
}

public FileUploader(String existingFileName, String urlString) {

    this.exsistingFileName = existingFileName;
    this.urlString = urlString;

}

只需在构造函数中传递existingFileName和urlString,文件就会被上传。

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接