简体   繁体   中英

Upload picture to server

I am using the following code: http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106

IT WORKS!

I want know that the picture I will send is a picture taken a few seconds ago with the camera. So.. I've created a simple method to take the picture and then this OnActivityResult:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_PIC_REQUEST) {
        //2
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        //3
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        //4
        File file = new File(Environment.getExternalStorageDirectory()+File.separator + "guasto.jpg");

        try {
            file.createNewFile();
            FileOutputStream fo = new FileOutputStream(file);
            //5
            fo.write(bytes.toByteArray());
            fo.close();

         uploadFile(uploadFilePath + "" + uploadFileName); //this should call the working method to upload the picture

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

The problem is that the upload won't work and it stops right before executing this line of code:

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

What should I do to resolve the problem...? Thank you very much

Try Following Code. Create an async task and add the code in doInBackground method. You will get InputStream's object in return.

You should use Multipart entity.

        File file = new File(selectedImage);
        ContentBody cbFile = new FileBody(file, "image/*");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart(RequestParams.POST, cbFile);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://yourwebserveraddress.com/apiname_or_whatever_path_it_is");

        httpPost.setEntity(reqEntity);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream is = httpEntity.getContent();

Where selectedImage is a path of your image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM