Angular 4 Rails 5 回形针文件上传

Angular 4 Rails 5 paperclip file upload

我正在开发一个使用 Angular 4 前端和 Rails 5 api 后端的项目。我正在尝试使用回形针上传视频,但我不知道为什么它没有保存到数据库中。所有参数都在日志中,但仍未保存。我修改了控制器,去掉了 require 语句,并多次重构了前端代码。我从各种来源尝试过一些技术,但没有奏效,我对到底发生了什么一无所知。任何输入将不胜感激。

这是我看到的日志

I, [2017-11-22T19:21:10.984681 #5898]  INFO -- : [6c0fdb67-31b6-43c6-8a79-e5ed2dfbec1e] Started POST "/movies" for 108.71.214.220 at 2017-11-22 19:21:10 +0000
I, [2017-11-22T19:21:11.001990 #5898]  INFO -- : [6c0fdb67-31b6-43c6-8a79-e5ed2dfbec1e] Processing by MoviesController#create as HTML
I, [2017-11-22T19:21:11.002088 #5898]  INFO -- : [6c0fdb67-31b6-43c6-8a79-e5ed2dfbec1e]   Parameters: {"video"=>#<ActionDispatch::Http::UploadedFile:0x000055a94d4e5970 @tempfile=#<Tempfile:/tmp/RackMultipart20171122-5898-17o86vd.mp4>, @original_filename="SampleVideo_720x480_1mb.mp4", @content_type="video/mp4", @headers="Content-Disposition: form-data; name=\"video\"; filename=\"SampleVideo_720x480_1mb.mp4\"\r\nContent-Type: video/mp4\r\n">, "title"=>"Test Movie", "year"=>"1998", "plot"=>"Awesomeness"}
D, [2017-11-22T19:21:11.016579 #5898] DEBUG -- : [6c0fdb67-31b6-43c6-8a79-e5ed2dfbec1e]   ^[[1m^[[36mApiKey Load (0.3ms)^[[0m  ^[[1m^[[34mSELECT  "api_keys".* FROM "api_keys" WHERE "api_keys"."client" =  LIMIT ^[[0m  [["client", "z8CSVtE3qejMxs4FFwYmKA"], ["LIMIT", 1]]
I, [2017-11-22T19:21:11.021183 #5898]  INFO -- : [6c0fdb67-31b6-43c6-8a79-e5ed2dfbec1e] Redirected to http://localhost:4200
I, [2017-11-22T19:21:11.021266 #5898]  INFO -- : [6c0fdb67-31b6-43c6-8a79-e5ed2dfbec1e] Filter chain halted as :authorized rendered or redirected
I, [2017-11-22T19:21:11.021376 #5898]  INFO -- : [6c0fdb67-31b6-43c6-8a79-e5ed2dfbec1e] Completed 302 Found in 19ms (ActiveRecord: 5.5ms)

模板

<div class="container">
    <h1>Movie Add Form</h1>
    <form [formGroup]="newForm" (ngSubmit)="upload()">
        <div class="form-group">
            <label for="title">Title:</label>
            <input 
                type="text" 
                name="title" 
                class="form-control" 
                formControlName="title"
            >

            <label for="year">Year:</label>
            <input 
                type="text" 
                name="year" 
                class="form-control" 
                formControlName="year"
            >

            <label for="plot">Plot:</label>
            <input 
                type="text" 
                name="plot" 
                class="form-control" 
                formControlName="plot"
            >
        </div>

        <div class="form-group">
            <input type="file" #fileInput placeholder="Upload file..." accept="video/mp4">
        </div>

        <div class="form-group">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>

组件

export class DvdNewComponent implements OnInit {
    newForm: FormGroup
    @ViewChild('fileInput') fileInput;

    constructor(private dvdService: DvdService,
                            private router: Router) { }

    ngOnInit() {
        this.newForm = new FormGroup({
            'title': new FormControl(null, Validators.required),
            'year': new FormControl(null, Validators.required),
            'plot': new FormControl(null, Validators.required)
        })
    }

    upload() {
        const movieFile = this.fileInput.nativeElement.files[0];

        this.dvdService.uploadMovie(movieFile, this.newForm.value)
            .subscribe(
                (data) => {
                    console.log('data ' + data)
                },
                (err: HttpErrorResponse) => {
                    console.log(err)
                },
                () => {
                    this.router.navigate(['/library'])
                }
            )
    }
}

服务

uploadMovie(fileToUpload: File, form): Observable<Movie> {
        const formData = new FormData();
        formData.append('video', fileToUpload)
        formData.append('title', form.title)
        formData.append('year', form.year)
        formData.append('plot', form.plot)
        const headers = new Headers();
        headers.delete('Content-Type');
        headers.append('access-token', this.tokenService.currentAuthData.accessToken)
        headers.append('client', this.tokenService.currentAuthData.client)
        const options = new RequestOptions({ headers: headers });

        return this.http.post(this.moviesURL + '/movies', formData, options)
        .map((res) => res.json())
    }

支持控制器

def create
                movie = Movie.new(movie_params)

                if movie.save
                        render json: movie, status: 201
                else
                        render json: { errors: movie.errors }, status: 422
                end
        end

def movie_params
                        params.permit(:title, :year, :plot, :video, :video_url)
                end

看了评论,查看了rack-cors,发现已经启用了。接下来,我检查了授权系统,经过一番挖掘后发现客户端 ID 不匹配。这是因为前端被路由到错误的端点。因此,我通过插入正确的端点解决了问题,现在代码可以正常工作了。