无法使用 ng-file-upload 和 laravel 正确上传

could not upload properly using ng-file-upload and laravel

我正在尝试实现一项功能,以便用户能够为我们的公司页面上传个人资料照片。我在 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);
        }
    }
}

您的后端需要名为 "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>

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

顺便说一句:当验证失败时,后端可以 return 状态 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)
});