【问题标题】:Angular 4 Rails 5 paperclip file uploadAngular 4 Rails 5 回形针文件上传
【发布时间】:2018-05-06 17:17:49
【问题描述】:

我正在开发一个使用 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" = $1 LIMIT $2^[[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吗?为了使 Angular 与 Rails 一起正常工作,这是必要的

标签: ruby-on-rails angular file-upload paperclip ruby-on-rails-5


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    相关资源
    最近更新 更多