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

时间:2017-05-25 15:32:01

标签: php android angularjs image onsen-ui

我有一个使用Monaca / Onsen UI和AngularJS构建的跨平台应用程序。 该应用程序允许用户拍摄图像(照片),这是按预期工作。

接下来,我想将图像上传到我的服务器以供存储和将来使用。

我的应用程序图像捕获工作正常,我已经在出现的服务器上实现了PHP解决方案,但我似乎无法看到图像。

我的捕获和上传应用程序代码如下所示(目前我只是访问图像库并选择要测试的图像 - 而不是捕获它们 - 但两种解决方案都有效):

$scope.takePicture = function getImage() {
    navigator.camera.getPicture(uploadPhoto, function (message) {
        alert('get picture failed');
    }, {
        quality: 100, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
    });
}

function uploadPhoto(imageURI) {
    var options = new FileUploadOptions();
    options.fileKey = "file";
    options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
    options.mimeType = "image/jpeg";
    var params = new Object();
    params.value1 = "test";
    params.value2 = "param";
    options.params = params;
    options.chunkedMode = false;

    var ft = new FileTransfer();
    ft.upload(imageURI, "http://mysite/public/api/savephotos.php", function (result) {
        alert("Success: " + JSON.stringify(result)); // Success: {"bytesSent":42468,"responseCode":200,"response":"","objectId":""}
    }, function (error) {
        alert("Fail: " + JSON.stringify(error));
    }, options);
}

成功响应中,似乎正在发送图像,但是当我检查要将图像保存到的文件夹时( C:\ xampp \ htdocs \ public \ api \ upload ),文件夹为空。服务器端详细信息是使用AWS上托管的Laravel框架的Sximo模板。

处理服务器端保存的PHP代码如下所示:

<?php
    // Connect to Database
    $DB_HOST = 'localhost';
    $DB_USER = 'root';
    $DB_PASS = '';
    $DB_NAME = 'myDB';

    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    // Allow Headers
    header('Access-Control-Allow-Origin: *');
    $new_image_name = urldecode($_FILES["file"]["name"]).".jpg";
    // Move files into upload folder
    move_uploaded_file($_FILES["file"]["tmp_name"], 'C:\xampp\htdocs\public\api\upload'.$new_image_name);

mysqli_close($mysqli);

但是, C:\ xampp \ htdocs \ public \ api \ upload 为空 - 没有向其发送图像。我有一个名为 uploadimage 的文件已被发送到目录* C:\ xampp \ htdocs \ public \ api *,似乎每次测试都会更新 - 但这是一个空的(0kb)文件。

我在哪里错了?

1 个答案:

答案 0 :(得分:0)

这是我用来将图库从应用程序发送到服务器的asynktask

public static class requestPostReportPhoto extends AsyncTask<String, Void, String> {

    Bitmap image;
    String JSON_STRING;

    @Override
    protected void onPreExecute(){
        String fileUrl = Environment.getExternalStorageDirectory()+"/"+Environment.DIRECTORY_DCIM+"/"+"albumName"+"/"+"photoName";
        image = BitmapFactory.decodeFile(fileUrl);

    }

    @Override
    protected String doInBackground(String... params) {
        String fileUrl = Environment.getExternalStorageDirectory()+"/"+Environment.DIRECTORY_DCIM+"/"+"albumName"+"/"+"photoName";

        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        HttpURLConnection connection = null;
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String response = "Error";



        String urlString = "yourUrlServer";

        try {
            File file = new File(fileUrl);
            FileInputStream fileInputStream = new FileInputStream(file);
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true); // Allow Inputs
            connection.setDoOutput(true); // Allow Outputs
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.addRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);


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

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + "PHOTONAME" + "\"" + lineEnd);
            dos.writeBytes(lineEnd);



            Log.d("MediaPlayer", "Headers are written");

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];


            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);
            }


            dos.writeBytes(lineEnd);

            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            StringBuilder responseSB = new StringBuilder();
            int result = connection.getResponseCode();
            BufferedReader br;
            // 401 - 422 - 403 - 404 - 500
            if (result == 401 || result == 422 || result == 403 || result == 404 || result == 500)
            {
                br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            }
            else {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            }
            while ( (JSON_STRING = br.readLine()) != null)
                responseSB.append(JSON_STRING+ "\n");

            Log.d("MediaPlayer","File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
            br.close();


            response = responseSB.toString().trim();

        } catch (IOException ioe) {
            Log.d("MediaPlayer", "error: " + ioe.getMessage(), ioe);
        }

        return response;

    }


    @Override
    protected void onPostExecute(String result) {
        Log.d("SERVER RESPONSE ->",result)
    }





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

}