Phonegap + Laravel 4 How to upload file

2020-07-30 10:45发布

I answered this question myself so that others don't face the problems i did.

1条回答
做自己的国王
2楼-- · 2020-07-30 11:06

The Client Side(Javascript Code) : It took me a while to figure out how to use the file upload feature in phonegap while using laravel 4 on the server. This is for others who might be looking for some help :

Ensure that :

  • public/images(or any other destination folder you wish to upload fie folder is writable or else you will get error code : 1
  • Values of options.fileKey must match Input::file(options.fileKey)->move()
  • You make a post request.

$('.upload').on('click',function() {

              navigator.camera.getPicture(cameraSuccess,cameraFail,
                {
                  quality: 50,
                  destinationType: Camera.DestinationType.FILE_URI,
                  mediaType: Camera.MediaType.PICTURE,
                  sourceType : Camera.PictureSourceType.PHOTOLIBRARY });

        });

  function cameraSuccess(imageURI)
          {

              //set file upload options
               var options = new FileUploadOptions();

                    options.fileKey="file";
                    options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
                    options.mimeType="image/jpeg";
                    options.chunkedMode = false;


                    var ft = new FileTransfer();

                    ft.upload(imageURI, encodeURI(url+'/file-upload'), win, fail, options);


            function win(r) {
                console.log("Code = " + r.responseCode);
                console.log("Response = " + r.response);
                console.log("Sent = " + r.bytesSent);
            }

            function fail(error) {

                console.log("An error has occurred: Code = " + error.code);
                console.log("upload error source " + error.source);
                console.log("upload error target " + error.target);
            }

The Server Side(Laravel) Code

Route::post('/file-upload',function()
{
    //I am storing the image in the public/images folder 
    $destinationPath = 'images/';

    $newImageName='MyImage.jpg';

    //Rename and move the file to the destination folder 
    Input::file('file')->move($destinationPath,$newImageName);

}

That is all that is required on the server side. After a successful upload the success callback function win will run.

查看更多
登录 后发表回答