【问题标题】:Sending image to webservice using asynctask使用 asynctask 将图像发送到 Web 服务
【发布时间】:2014-11-13 12:15:47
【问题描述】:

我有一个应用程序,它可以拍照并向我发送给定图片的 uri。 接下来,我想做的是将这张图片发送到我的网络服务。

但是,一旦我尝试过,我遇到了一个我以前遇到过的错误,它与 asynctask 有关。所以试图解决它,我有一个 HttpManager 类,它包含有关如何连接到 web 服务、url 本身以及它处理图像 uri 的位置的信息。

public static String uploadImageToWebservice(String uri, String imageUri) {
    HttpURLConnection connection = null;
    int responseCode = 0;
    String image = "";
    try {

        URL url = new URL(uri + imageUri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "text/plain");

        /*
        * String userpassword = adminUser + ":" + adminPassword; String
        * encodedAuthorization = DatatypeConverter
        * .printBase64Binary(userpassword.getBytes("UTF-8"));
        * connection.setRequestProperty("Authorization", "Basic " +
        * encodedAuthorization);
        */

        InputStream is = connection.getInputStream();
        image = is.toString();
        responseCode = connection.getResponseCode();
        connection.disconnect();
    } catch (IOException e) {
        Log.e("URL", "failure response from server >" + e.getMessage()
                + "<");

    } finally {
        if (connection != null) {
            connection.disconnect();
        }

    }
    return image;
}

这就是我在活动中处理此方法的方式。

private void submitImage(String uri) {
    HttpAsyncTask at = new HttpAsyncTask();
    at.execute(uri);

}

    private class HttpAsyncTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            String image = HttpManager.uploadImageToWebservice(params[0],
                    params[1]);
            return image;
        }

    }

然后我使用 web 服务的 Uri 在 oncreate 中调用 submitImage 方法。

但我有点纠结于将图像本身的 uri 放在哪里以便发送。我只是觉得我错过了一些东西,我不知道它在哪里。希望它能够理解这一切。

提前致谢!

【问题讨论】:

    标签: android image web-services android-asynctask uri


    【解决方案1】:

    使用代码上传图片

                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;
    
                       FileInputStream fileInputStream = new FileInputStream("sourcefile");
                        URL url = new URL("URL");
    
                        // Open a HTTP connection to the URL
                        conn = (HttpURLConnection) url.openConnection();
                        conn.setDoInput(true); // Allow Inputs
                        conn.setDoOutput(true); // Allow Outputs
                        conn.setUseCaches(false); // Don't use a Cached Copy
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("Connection", "Keep-Alive");
                        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                        conn.setRequestProperty("Content-Type",
                                "multipart/form-data;boundary=" + boundary);
                        conn.setRequestProperty("bill", sourceFileUri);
    
                        dos = new DataOutputStream(conn.getOutputStream());
    
                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
                                + sourceFileUri + "\"" + lineEnd);
    
                        dos.writeBytes(lineEnd);
    
                        // create a buffer of maximum size
                        bytesAvailable = fileInputStream.available();
    
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        buffer = new byte[bufferSize];
    
                        // read file and write it into form...
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    
                        while (bytesRead > 0) {
    
                            dos.write(buffer, 0, bufferSize);
                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    
                        }
    
                        // send multipart form data necesssary after file
                        // data...
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    
                        // Responses from the server (code and message)
                        serverResponseCode = conn.getResponseCode();
                        // String serverResponseMessage = conn
                        // .getResponseMessage();
    
                        if (serverResponseCode == 200) {
                            statud = "uploaded";
                            // messageText.setText(msg);
                            // Toast.makeText(ctx, "File Upload Complete.",
                            // Toast.LENGTH_SHORT).show();
                            // System.out.println("Uploaded successfyuly http: 200");
                            // recursiveDelete(mDirectory1);
    
                        }
    
                        // close the streams //
                        fileInputStream.close();
                        dos.flush();
                        dos.close();
    

    php代码

    <?php
    
       $uploads_dir = './images/';
       $tmp_name = $_FILES['bill']['tmp_name'];
       $pic_name = $_FILES['bill']['name'];
    
       if (move_uploaded_file($tmp_name, $uploads_dir.$pic_name )) {
       echo "uploaded"; 
       }
    
    ?>
    

    【讨论】:

    • 这行不通,因为我正在使用 android,所以我需要包含 asynctask。否则,如果不使用它,我会得到一个异常。
    • 你必须在 asynctask 的 doinbackground 方法中使用这段代码 ok
    • 我很快就会试试这个!
    • 你的代码@raj 中没有说明很多变量 - 你能帮我解决这个问题吗?
    • 如果你需要上传图片到服务器,首先使用Base64编码成String,然后在服务器端解码成图片。这将有助于减少android应用程序中的内存异常处理。
    猜你喜欢
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多