Phonegap + Laravel 4如何上传文件

时间:2013-10-08 17:23:51

标签: cordova laravel laravel-4 phonegap-plugins

我自己回答了这个问题,以便其他人不会面对我所遇到的问题。

1 个答案:

答案 0 :(得分:2)

客户端(Javascript代码): 我花了一些时间来弄清楚如何在服务器上使用laravel 4时在phonegap中使用文件上传功能。这适用于可能寻求帮助的其他人:

确保:

  • 公开/图片(或您希望上传的任何其他目标文件夹,文件夹是可写的,否则您将获得错误代码:1
  • options.fileKey 的值必须与Input::file(options.fileKey)->move()
  • 匹配
  • 您发帖子请求。
  

$(' .upload&#39)上('单击',()的函数               {

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

服务器端(Laravel)代码

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

}

这就是服务器端所需的全部内容。成功上传后,将运行成功回调函数 win