【问题标题】:Unable to upload the image to server on android app using php api无法使用 php api 将图像上传到 android 应用程序上的服务器
【发布时间】:2015-11-25 07:25:42
【问题描述】:

我正在 android 中创建一个用于在服务器上上传图片的应用程序。为此,我在 php.ini 中创建了一个 api。但是我无法在服务器上上传图片 这是我的安卓代码

FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                // URL url = new URL(
                // "http://www.mystashapp.com/Loyalty/mobileservice.php?action=upload_image");
                URL url = new URL(
                        "http://www.mvcangularworld.com/api.php");
                // 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("uploaded_file", fileName);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + fileName + "\"" + 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();

                InputStreamReader isr = new InputStreamReader(
                        conn.getInputStream());

                BufferedReader br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    sb.append(line);
                }

                isr.close();
                br.close();

                JSONObject json = new JSONObject(sb.toString());
                filePath = json.optString("filepath");

                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) {
                    // Toast.makeText(context, "File Upload Completed.",
                    // Toast.LENGTH_LONG).show();
                    Log.e("message", "image upload complete");
                }

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

这是我的 php api

<?php

$target_path = 'andriod/';  // Path to move uploaded files
$response = array();

$file_upload_url = $target_path;
//$filename = $_POST['filename']; 
 $server_ip = "http://www.mvcangularworld.com";//gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = $server_ip . '/' . $target_path;

 if (isset($_FILES['fileName']['name'])) {
    $target_path = $target_path . basename($_FILES['fileName']['name']);
    // reading other post parameters


    $response['file_name'] = basename($_FILES['fileName']['name']);

    try {
        // Throws exception incase file is not being moved
        if (!move_uploaded_file($_FILES['fileName']['tmp_name'], $target_path)) 
        {
            // make error flag true
            $response['error'] = true;
            $response['message'] = 'Could not move the file!';
        }

        // File successfully uploaded
         //echo $file_upload_url . basename($_FILES['filename']['name']);
        $response['message'] = 'File uploaded successfully!';
        $response['error'] = false;
        $response['file_path'] = $file_upload_url . basename($_FILES['fileName']['name']);
    } 
    catch (Exception $e) {
        // Exception occurred. Make error flag true
        $response['error'] = true;
        $response['message'] = $e->getMessage();
    }
} else { 
    // File parameter is missing
    $response['error'] = true;
    $response['message'] = $_FILES['fileName']['name'];
}

// Echo final json response to client
echo json_encode($response, JSON_UNESCAPED_SLASHES);
?>

它总是让我陷入 else 状态并给我这个响应作为回报

{"error":true,"message":null}

我无法将我的文件上传到服务器。任何人都知道这个问题,请告诉我。

【问题讨论】:

    标签: php android file-upload


    【解决方案1】:

    改变这一行

    conn.setRequestProperty("uploaded_file", fileName);
    

    conn.setRequestProperty("fileName", fileName);
    

    还有这个

    dos.writeBytes("Content-Disposition: form-data; name=\"filename\";filename=\""
                        + fileName + "\"" + lineEnd);
    

    您在 php 中以 filename 的形式检索文件,但使用名称 uploaded_file 传递它。改个名字就行了

    【讨论】:

      【解决方案2】:

      1) 将图像转换为字节数组或base64(字符串格式)的字符串。

      reference1

      reference2

      2) 你的 php api,尝试以 RESTful (as JSON) 或普通方式接收字符串。

      3) 在您的 php 中,将字符串转换为图像。但应该限制图像格式(例如移动设备将发送.jpeg,php将转换字符串.jpeg)

      reference3

      reference4

      你可以在谷歌搜索“android 上传图片到服务器”

      【讨论】:

        猜你喜欢
        • 2016-01-02
        • 2017-10-26
        • 2020-12-25
        • 1970-01-01
        • 1970-01-01
        • 2020-11-05
        • 2018-08-17
        • 2017-06-09
        • 1970-01-01
        相关资源
        最近更新 更多