如何在Android中发送图像或文本文件

时间:2014-05-15 11:16:33

标签: android androidhttpclient

实际上我正在开发一个应用程序,它使用json作为名称 - 值对发送提交表单进行服务器通信。但问题是现在我想在表单提交期间发送图像或文本文件,如何在表单提交期间发送图像或文本文件。有没有正确的程序?

2 个答案:

答案 0 :(得分:1)

尝试以下代码将图片上传到服务器:

private class ImageUploader extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
            String result = "";

            // Client-side HTTP transport library
            HttpClient httpClient = new DefaultHttpClient();

            // using POST method
            HttpPost httpPostRequest = new HttpPost(imagePostUrl);
            try {

                // creating a file body consisting of the file that we want to
                // send to the server
                FileBody bin = new FileBody(imageFile);

                /**
                 * An HTTP entity is the majority of an HTTP request or
                 * response, consisting of some of the headers and the body, if
                 * present. It seems to be the entire request or response
                 * without the request or status line (although only certain
                 * header fields are considered part of the entity).
                 * 
                 * */
                MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
                multiPartEntityBuilder.addPart("images[1]", bin);
                httpPostRequest.setEntity(multiPartEntityBuilder.build());

                // Execute POST request to the given URL
                HttpResponse httpResponse = null;
                httpResponse = httpClient.execute(httpPostRequest);

                // receive response as inputStream
                InputStream inputStream = null;
                inputStream = httpResponse.getEntity().getContent();

                if (inputStream != null)
                    result = convertInputStreamToString(inputStream);
                else
                    result = "Did not work!";
                return result;
            } catch (Exception e) {

                return null;
            }

            // return result;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            uploadStatus.setText("Uploading image to server");
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            uploadStatus.setText(result);
        }

    }

    private static String convertInputStreamToString(InputStream inputStream)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

答案 1 :(得分:0)

对于文件,请尝试以下代码:

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    // show error
}