如何将从Gallery中选择的图像上传到android中的PHP服务器上?

时间:2017-05-28 13:39:39

标签: php android android-asynctask image-uploading android-image

因此,我可以成功地让用户从图库中选择图像而没有任何问题(我已经通过将所选图像设置到ImageView上来检查它)。我已经创建了一个AsyncTask类来进行上传。我在这个函数的帮助下将Image作为base64编码的String传递(我认为它工作正常):

public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }  

我还将会话用户名作为参数传递(用于命名将要上传的图像)。

这里是AsyncTask活动:

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class BackgroundPhotoUpload extends AsyncTask<String, String, String> {
    String encodedImage;
    Context context;
    String usernameSignUp;

    BackgroundPhotoUpload(Context ctx) {
        this.context = ctx;
    }

    @Override
    protected String doInBackground(String... params) {
        usernameSignUp = params[0];
        encodedImage = params[1];
        try {
            String loginUrl = "xxx";
            URL url = new URL(loginUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String postData = URLEncoder.encode("encodedImage", "UTF-8") + "=" + URLEncoder.encode(encodedImage, "UTF-8") + "&"
                    + URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(usernameSignUp, "UTF-8");
            bufferedWriter.write(postData);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result = "";
            String datarecieved = "";
            while ((datarecieved = bufferedReader.readLine()) != null) {
                result += datarecieved;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    protected void onPreExecute() {
        Toast.makeText(context,"Starting Upload", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPostExecute(final String result) {
        Toast.makeText(context, "Uploaded!", Toast.LENGTH_SHORT).show();
    }
}

这是我如何从主类调用AsyncTask类:

BackgroundPhotoUpload backgroundWorker = new BackgroundPhotoUpload(this);
backgroundWorker.execute(usernameSignUp, encodedString);

在部署应用程序时,我只看到第一个Toast消息:

@Override
    protected void onPreExecute() {
        Toast.makeText(context,"Starting Upload", Toast.LENGTH_SHORT).show();
    }

应用程序在发送第二个Toast消息之前崩溃:

@Override
    protected void onPostExecute(final String result) {
        Toast.makeText(context, "Uploaded!", Toast.LENGTH_SHORT).show();
    } 

当我手动输入输入时,服务器上托管的PHP脚本运行得非常好。所以我认为它是AsyncTask类的一个问题。

但不管怎样,这里是PHP脚本:

<?php 
    require 'init.php';
    if(isset($_GET["encodedImage"]) && isset($_GET["username"])) {
        $imageEncoded = $_GET["encodedImage"];
        $username = $_POST["username"];
        $imageDecoded = base64_decode($imageEncoded);
        $path = "images/profilePic_".$username.".jpg";
        file_put_contents($path,$imageDecoded);
        echo "Successfully updated!";
    }
    else {
            echo "An error occurred.";
    }

?>

令人惊讶的是,为什么只有Uploading Image部分会崩溃应用程序。我做了一个登录和一个signUp页面,其中包含相同的AsyncTask Activity(显然是不同的targetURL和标题),它们完全正常。

此问题的任何解决方案?

0 个答案:

没有答案