将图片上传到服务器

时间:2014-09-29 08:59:37

标签: java android image upload camera

我使用以下代码: http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106

IT工作!

我想知道我将发送的图片是几秒钟前用相机拍摄的照片。 所以..我已经创建了一个简单的方法来拍照,然后是这个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();
        }
    }

问题是上传无法正常工作,并且在执行此行代码之前就会停止:

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

我该怎么做才能解决问题......? 非常感谢你

1 个答案:

答案 0 :(得分:0)

尝试以下代码。创建一个异步任务并在doInBackground方法中添加代码。您将获得InputStream的对象作为回报。

您应该使用Multipart实体。

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

其中selectedImage是图像的路径。