【问题标题】:could not upload properly using ng-file-upload and laravel无法使用 ng-file-upload 和 laravel 正确上传
【发布时间】:2015-11-28 18:17:34
【问题描述】:

我正在尝试实现一项功能,以便用户能够为我们的公司页面上传个人资料照片。我在 Angular 中使用 ng-file-upload 插件:https://github.com/danialfarid/ng-file-upload

我按照文档中的一个示例上传照片:

    function uploadPic ( file ) {
        file.upload = Upload.upload( {
            url: 'api/companyprofile/upload_logo',
            method: 'POST',
            sendFieldsAs: 'form',
            headers: {
                'my-header': 'my-header-value'
            },
            file: file,
            fileFormDataName: 'myLogo.png'
        } );

        file.upload.then( function ( response ) {
            $timeout( function () {
                file.result = response.data;
            } );
        }, function ( response ) {
            if ( response.status > 0 )
                logger.error( response )
        } );

        file.upload.progress( function ( evt ) {
            // Math.min is to fix IE which reports 200% sometimes
            file.progress = Math.min( 100, parseInt( 100.0 * evt.loaded / evt.total ) );
        } );
    }

这是它的html

                            <form name="myForm" enctype="multipart/form-data">
                                <fieldset>
                                    <legend>Upload on form submit</legend>
                                    <br>Photo:
                                    <input type="file" ngf-select ng-model="picFile" name="cp_logo" accept="image/*" ngf-max-size="2MB" required>
                                    <i ng-show="myForm.file.$error.required">*required</i>
                                    <br>
                                    <i ng-show="myForm.file.$error.maxSize">File too large 
      {{picFile.size / 1000000|number:1}}MB: max {{picFile.$errorParam}}</i>
                                    <img ng-show="myForm.file.$valid" ngf-src="!picFile.$error && picFile" class="thumb">
                                    <br>
                                    <button ng-click="vm.uploadPic(picFile)">Submit</button>
                                    <span class="progress" ng-show="picFile.progress >= 0">
    <div style="width:{{picFile.progress}}%" 
        ng-bind="picFile.progress + '%'"></div>
  </span>
                                    <span ng-show="picFile.result">Upload Successful</span>
                                    <span class="err" ng-show="errorMsg">{{errorMsg}}</span>
                                </fieldset>
                                <br>
                            </form>

问题是我收到状态码 200,告诉我它已成功上传照片,但实际上并没有。给我一个空洞的回应。我做错了什么?

免责声明:我不了解 php,但这是我们后端开发人员提供的后端代码。这可能会有所帮助

/**
 * Upload a Company Logo (Synchronous).
 * @route GET - prefix/companyprofile/upload_logo
 *
 * @return json
 */
public function uploadLogo() 
{
    // get the company profile object
    $cProfile = CompanyProfile::first();
    // get all inputs from the form
    $input = Input::all();
    // needs validation
    $validator = Validator::make(Input::all(), ['cp_logo' => 'image|max:'.$this->max_filesize]);
    if ($validator->fails()) {
        return array('error' => $validator->messages());
    }
    // if there is a cp_logo store in $file variable
    if($file = array_get($input,'cp_logo')) {
        // delete old company logo
        $this->deleteOldCompanyLogo($cProfile);
        // concatenate the filename and extension
        $input['filename'] = $this->generateFileName($file);
        // save the company logo filename in the database
        $this->saveCompanyLogo($cProfile, $input['filename']);
        try {
            // upload the files to the file server
            Storage::disk(env('FILE_STORAGE'))->put($input['filename'],  File::get($file));
            return response()->json(['status' => 'Upload successful', 'filename' => $input['filename']]);
        } catch(\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }
}

【问题讨论】:

  • 查看文件是否真的在浏览器的网络选项卡中发送。如果是这种情况,那么这是 php 代码没有正确保存它的问题。如果实际收到文件,您可以要求后端开发人员记录。
  • 我尝试在 file.upload 对象 @danial 字段中放置另一个参数:{cp_logo: 'filename.png'},它现在给了我一个 {"error":{"cp_logo" 的响应:["cp logo必须是图片。"]}}
  • 我的简短回答:fileFormDataName: 'cp_logo'
  • 成功了!太感谢了!你能给我解释一下这个原因吗? @aifarfa
  • 是的,一个简单的 html 表单使用 &lt;input name="..." 作为数据键,但 ng-file-upload 用 fileFormDataName 字段覆盖它。 :)

标签: angularjs laravel ng-file-upload


【解决方案1】:

您的后端期望输入名为“cp_logo”

function uploadPic(file) {
    if (!file || file.$error) {
        logger.error(file);
        return;
    }
    file.upload = Upload.upload({
        url: 'api/companyprofile/upload_logo',
        method: 'POST',
        sendFieldsAs: 'form',
        headers: {
            'my-header': 'my-header-value'
        },
        file: file,
        fileFormDataName: 'cp_logo' //<-- here is your POST data key send to server
    });

因为在您的 html 输入中名为“cp_logo”

<input type="file" ngf-select ng-model="picFile" name="cp_logo" accept="image/*" ngf-max-size="2MB" required>

您的验证表达式应该是.. myForm.cp_logo.$errormyForm.cp_logo.$valid

还要在发送前仔细检查上传输入

HTML

<img ng-show="myForm.cp_logo.$valid" ngf-src="!picFile.$error && picFile" class="thumb">
<br>
<button ng-click="vm.uploadPic(picFile)" ng-disabled="!myForm.$valid" >Submit</button>

^ 如果这个按钮被禁用,显然输入有问题

顺便说一句:验证失败时,后端可能会返回状态 200(OK)

你可以检查json响应

file.upload.then(function(response) {
    $timeout(function() {
        logger.log(response.data); 
        if(response.data.error){
            //something went wrong?
        }
        file.result = response.data;
    });
}, function(response) {
    if (response.status > 0)
        logger.error(response)
});

【讨论】:

  • 我检查了 json 响应,这很奇怪,因为它说 status: 200 statusText: "OK"
  • 我尝试了一个没有 ng-file-upload 或 angular 的简单 html 文件上传,它工作得很好
  • 我丢失了 fileFormDataName: 'cp_logo'
猜你喜欢
  • 1970-01-01
  • 2017-08-16
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 2015-12-08
  • 2016-11-09
  • 1970-01-01
相关资源
最近更新 更多