简体   繁体   English

Angular 4 Rails 5回形针文件上传

[英]Angular 4 Rails 5 paperclip file upload

I am working on a project using a Angular 4 frontend and a Rails 5 api backend. 我正在使用Angular 4前端和Rails 5 api后端进行项目。 I am trying to upload video using paperclip, but I have no idea why it is not saving to the database. 我正在尝试使用回形针上传视频,但是我不知道为什么它没有保存到数据库中。 All the parameters are there in the log it still not saving. 日志中仍然存在所有参数,但仍不保存。 I've modified the controller taking out the require statement and refactored the frontend code serveral times. 我修改了控制器,取出了require语句,并重构了前端代码的服务器时间。 There are serveral techniques I've tried from various sources that have not worked and i am drawing a blank as to what exactly is going on. 我曾尝试过多种服务器技术,但各种方法均未奏效,而我正在为正在发生的事情画上空白。 Any input would be greatly appreciated. 任何投入将不胜感激。

this is a log of what im seeing 这是我看到的日志

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)

template 模板

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

component 零件

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'])
                }
            )
    }
}

service 服务

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

Backed controller 支持的控制器

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

After reading the comments, I checked rack-cors and found that it was enabled. 阅读评论后,我检查了机架式芯线,发现它已启用。 Following, I checked the authorization system and found after after some digging that the client id was not matching. 接下来,我检查了授权系统,经过一番挖掘后发现客户端ID不匹配。 This was do to the frontend being routed to the wrong endpoint. 这样做是因为前端被路由到错误的端点。 So, I fixed the problem by inserting the correct endpoint and now the code works. 因此,我通过插入正确的端点解决了问题,现在代码可以正常工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM