繁体   English   中英

将图片上传到服务器

[英]Upload picture to server

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

有用!

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

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

尝试以下代码。 创建一个异步任务,并在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是图像的路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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