Android Java / PHP上传图片404

时间:2016-01-18 18:35:52

标签: java php android post image-uploading

我目前正在尝试实施个人资料图片系统,但它似乎根本不起作用。我很确定问题是我正在使用的php脚本。我想强调我所有其他PHP脚本都在工作,所以用于添加用户,获取用户详细信息甚至用于获取配置文件图像的脚本。我不知道它可能是什么,所以我也包括应用程序源代码。如果我尝试发送一个帖子到php文件,我总是得到一个404,而不仅仅是在应用程序中,因此它必须是PHP脚本,但我不知道这里可能是什么问题。上传的写入过程有效但使用InputStreamReader不起作用。我真的希望有人可以帮助我,在这个问题上提出的解决方案似乎都不适合我。

调用异步任务:

Uri filePath = data.getData();
Log.d("debugshit", "in if statement pic change");
try {
    final Bitmap profilePic = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
    ServerRequest sr = new ServerRequest(this, "Updating Profile...");
    sr.updateProfilePic(activeUser, profilePic, new ServerCallback() {
        @Override
        public void done(User returnedUser) {

        }

        @Override
        public void done(boolean success) {
            if (success) {
                ((ImageView)header.findViewById(R.id.navProfileImage)).setImageBitmap(profilePic);
                Toast.makeText(MainActivity.this, "Profile Picture updated", Toast.LENGTH_SHORT).show();
            }
        }
    });
}
catch (IOException e) {
    e.printStackTrace();
}

服务器请求类:

public void updateProfilePic(User user, Bitmap profilePic, ServerCallback callback) {
        progressDialog.show();
        new UpdateProfilePicTask(user, profilePic, callback).execute();
    }

    public class UpdateProfilePicTask extends AsyncTask<Void, Void, Boolean> {

        User user;
        Bitmap profilePic;
        ServerCallback callback;

        public UpdateProfilePicTask(User user, Bitmap profilePic, ServerCallback callback) {
            this.user = user;
            this.profilePic = profilePic;
            this.callback = callback;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                URL url = new URL("http://server/set_profilepic.php");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setDoOutput(true);
                con.setDoInput(true);

                OutputStream os = con.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");

                ContentValues contentValues = new ContentValues();
                contentValues.put("id", user.getId());
                contentValues.put("img_name", user.getUsername() + "_" + Calendar.getInstance().getTimeInMillis() + ".png");
                contentValues.put("encoded_img", encodeImage(profilePic));

                Log.d("debugshit", encodeParams(contentValues));

                con.connect();
                osw.write(encodeParams(contentValues));
                osw.flush();

                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String response = br.readLine();
                Log.d("debugshit", response);

                br.close();
                osw.close();
                os.close();
                con.disconnect();

                return response.equals("OK");
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            progressDialog.dismiss();
            callback.done(success);

            super.onPostExecute(success);
        }
    }

private String encodeImage(Bitmap image) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        byte[] imageBytes = outputStream.toByteArray();
        return Base64.encodeToString(imageBytes, Base64.DEFAULT);
    }

    private String encodeParams(ContentValues values) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String, Object>> entrySet = values.valueSet();
        boolean first = true;

        for(Map.Entry entry : entrySet) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();

            if (first)
                first = false;
            else
                sb.append("&");

            sb.append(URLEncoder.encode(key, "UTF-8"));
            sb.append("=");
            sb.append(URLEncoder.encode(value, "UTF-8"));
        }
        return sb.toString();
    }

set_profilepic.php

<?php      

    header('Content-type: bitmap; charset=utf-8');

    $id = $_POST['id'];
    $imgname = $_POST['img_name'];
    $img = $_POST['encoded_img'];

    if (isset($imgname, $img)) {
        $decodedimg = base64_decode($img);
        $path = 'profile_images/' . $imgname;    

        $file = fopen($path, 'wb');
        $written = fwrite($file, $decodedimg);
        fclose($file);

        if ($written > 0) {
            $con = mysqli_connect("server", "user", "pw", "db");

            $statement = mysqli_prepare($con, "UPDATE User SET profilepic = ? WHERE id = ? ");

            mysqli_stmt_bind_param($statement, "si", $path, $id);
            $success = mysqli_stmt_execute($statement);

            mysqli_stmt_close($statement);
            mysqli_close($con);

            if ($success) {
                echo "OK";
            }
            else {
                echo "Error";
            }
        }
        else {
            echo "Error";
        }
    }
    else {
        echo "Error";
    }

?>

1 个答案:

答案 0 :(得分:0)

好吧,我设法解决了我的错误。问题是我必须更改我的权限才能使其正常工作。默认情况下禁用写入权限,因此我无法上传文件并引发404错误。