简体   繁体   中英

Uploading images from app to server using PHP

I have a cross platform app built using Monaca/Onsen UI and AngularJS. The app allows users to take images (photos) and this is working as intended.

Next, I want to upload the images to my server for storage and future use.

I have the app image capture working as intended and I have implemented a PHP solution on the server that appears to be working, but I cant seem to see the images.

My app code for capture and upload looks as follows (at the moment I just access the image library and select images for testing - rather than capturing them - but both solutions working):

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

From the success response it seems that images are being sent, but when I check the folder where the images are supposed to be saved to ( C:\\xampp\\htdocs\\public\\api\\upload ), the folder is empty. The server side details are Sximo template using Laravel framework hosted on AWS.

The PHP code that handles the server side saving looks as below:

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

However, the C:\\xampp\\htdocs\\public\\api\\upload is empty - with no images sent to it. I do have a file called uploadimage that has been sent to the directory *C:\\xampp\\htdocs\\public\\api* that appears to be updated with each test - but this is a empty (0kb) file.

Where am I going wrong with this?

This is the asynktask that I use to send image from the gallery app to server

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM