如何使用asynctask将图像从android上传到php

时间:2016-10-26 10:47:22

标签: php android image android-asynctask

大家。我被困在我正在研究的这个项目上。我希望能够从android库中上传图像,将该图像编码为base64字符串并发送到PHP Web服务,作为get变量,然后从另一端解码图像并按照我的意愿处理它。 / p>

到目前为止,我可以从图库中选择图像,甚至编码为base64字符串并存储在Android首选项中。

问题是,我认为并非所有字符串都被发送到PHP服务(有些被截断)。

为什么我这么认为?我的Log.d在不同位置转储时向我显示了不同的字符串。

获取图像和编码的代码是: -

private void galleryIntent()
{
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Please select a file"),1);
}

private String onSelectFromGalleryResult (Intent data) {

    if (data != null) {
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver() , data.getData()) ;
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;

        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) ;

        byte[] imageBytes = byteArrayOutputStream.toByteArray() ;

        Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ;

        return Base64.encodeToString (imageBytes, Base64.DEFAULT) ;
    } else {
        return null ;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    SharedPreferences sharedPreferences =  getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit() ;

    if (resultCode == Activity.RESULT_OK) {

        if (requestCode == 1) {
            /*Here we handle the image gotten from the gallery*/
            String encodedGalleryImage = onSelectFromGalleryResult(data);

           editor.putString("userEncodedGalleryImage" , encodedGalleryImage);

        } else if (requestCode == 0) {
            /*Here we handle the image that was take using the camera*/

        }

        editor.apply();
    }
}

这里我们称之为asynctask类

private void callAsynctask () {
  SharedPreferences sp = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);

    String userQuestionAttachement = sp.getString("userEncodedGalleryImage" , "") ;

Log.d("callingEncodedImage" , userQuestionAttachement) ;
}

我遇到的问题是来自Log.d的日志("选择图像库",Base64.encodeToString(imageBytes,Base64.DEFAULT));与Log.d不同(" callingEncodedImage",userQuestionAttachement);

两者都有相同的开头但不同的结局。我希望看到相同的角色。

有人可以帮我解决一下吗?

2 个答案:

答案 0 :(得分:1)

在Android中,

 new UploadFileAsync().execute("");



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

    @Override
    protected String doInBackground(String... params) {

        try {
  String sourceFileUri = "/mnt/sdcard/abc.png";

            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;
            File sourceFile = new File(sourceFileUri);

            if (sourceFile.isFile()) {

                try {
                    String upLoadServerUri = "http://website.com/abc.php?";

                    // open a URL connection to the Servlet
                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);
                    URL url = new URL(upLoadServerUri);

                    // 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) {

                        // messageText.setText(msg);
                        //Toast.makeText(ctx, "File Upload Complete.",
                        //      Toast.LENGTH_SHORT).show();

                        // recursiveDelete(mDirectory1);

                    }

                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                } catch (Exception e) {

                    // dialog.dismiss();
                    e.printStackTrace();

                }
                // dialog.dismiss();

            } // End else block


        } catch (Exception ex) {
            // dialog.dismiss();

            ex.printStackTrace();
        }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

在Php中,

    <?php


     if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
    $uploads_dir = './';
                            $tmp_name = $_FILES['bill']['tmp_name'];
                            $pic_name = $_FILES['bill']['name'];
                            move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
                            }
               else{
                   echo "File not uploaded successfully.";
           }

   ?>

答案 1 :(得分:0)

要使用 Multipart 上传图片,请按照以下步骤操作:

  1. 下载httpmime.jar文件并将其添加到 libs 文件夹中。

  2. 下载http client.jar文件并将其添加到 libs 文件夹中。

  3. 从后台线程或AsyncTask调用以下方法。

    public void executeMultipartPost() throws Exception {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "YOUR SERVER URL");
            ByteArrayBody bab = new ByteArrayBody(data, "YOUR IMAGE.JPG");
    
            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("IMAGE", bab);
    
            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();
    
            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
            System.out.println("Response: " + s);
        } catch (Exception e) {
            // handle exception here
            Log.e(e.getClass().getName(), e.getMessage());
        }
    }