使用JSonParser将图像上传到PHP服务器

时间:2015-12-04 10:00:42

标签: php android image-uploading

我正在尝试使用我的JSONParser类上传图片。这是课程:

    public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result = new StringBuilder();
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(final Context context,String url, String method,
                                      HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);


                conn.setReadTimeout(10*1000);//orijinal 10000

                conn.setConnectTimeout(15*1000);//orijinal 15000

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

            } catch (IOException e) {
                MyMethods.makeToastInAsync(context,context.getResources().getString(R.string.connProblem),Toast.LENGTH_LONG);
                e.printStackTrace();
            }

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {

            MyMethods.makeToastInAsync(context,context.getResources().getString(R.string.connProblem),Toast.LENGTH_LONG);

            e.printStackTrace();
        }

        conn.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jObj;
    }
}

SendImage类的异步部分:

protected JSONObject doInBackground(String... args) {

        try {

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
            String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);

            Log.d("Send Image", encodedImage);


            HashMap<String, String> dataTosend = new HashMap<>();
            dataTosend.put("image", encodedImage);
            dataTosend.put("name", sharedPreferences.getString("username", ""));

            JSONObject json = jsonParser.makeHttpRequest(SendImage.this,
                    UPLOAD_IMAGE_URL, "POST", dataTosend);

            if (json != null) {
                Log.d("JSON result", json.toString());

                return json;
            }


        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

因此,如您所见,首先我压缩图像并使用base64编码并返回String以使用JSONParser发送。

问题是,我可以发送不那么大的图像,但如果它超过6 mb(大约),我就无法发送。我收到了这个错误:

java.io.FileNotFoundException: http://example.com/uploadImage.php

和行错误:

   InputStream in = new BufferedInputStream(conn.getInputStream());
(E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of )

在我看来,我得到JSON异常,因为没有来自服务器的答案。但我不明白为什么我得到这个错误。

java.io.FileNotFoundException: http://example.com/uploadImage.php

是否可能,该服务器不接受传入的文件多于某些Mb?

编辑:当我将压缩率从50更改为10时,我可以上传我无法完成的图像。所以,我确信由于图像大小而发生错误。

setReadTimeout setConnectTimeout 超过之前发生此错误。

我的PHP代码:

<?php
if (!empty($_POST)) {


$name =$_POST["name"];
$image =$_POST["image"];

$decodedImage= base64_decode("$image");

$resultt=file_put_contents("images/" .$name. ".JPG",$decodedImage);

if($resultt){


    $response["success"] = 1;
        $response["message"] = "".$resultt. "";
        die(json_encode($response));

}
    $response["success"] = 0;
        $response["message"] = "Fail";
        die(json_encode($response));

}



?>

1 个答案:

答案 0 :(得分:0)

服务器可能有问题。

php.ini文件在您的服务器内。

PHP有几个配置选项来限制脚本消耗的资源。默认情况下,PHP设置为允许上传大小为2MB或更小的文件。

尝试在php.ini中增加以下值,例如:

memory_limit = 32M
upload_max_filesize = 24M
post_max_size = 32M
相关问题