Saving file via API in database using laravel and

2019-07-27 10:58发布

I have 2 questions...
1. When I send file Request in saveAttachment() method is empty ([]).
2. Is my procedure okay for saving file as binary in database?

Laravel Migration:

class CreateAttachmentsTable extends Migration
{
    public function up()
    {
        Schema::create('attachments', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->binary('content');
        });
    }
}

Laravel Controller:

public function saveAttachment(Request $request)
{
    if ($request->file) {
        $attachment = new Attachment();
        $attachment->content = $request->file;
        $attachment->save();
    }
}

Angular Component:

onFileChange(event) {
    if (event.target.files.length > 0) {
        this.service.saveAttachment(event.target.files[0]).subscribe();
    }
}

Angular Service:

saveAttachment(file: File) {
    return this.http.post(USER_API_URL + '/saveAttachment, { file: file });
}

Thanks.

1条回答
仙女界的扛把子
2楼-- · 2019-07-27 11:22

I found a solution but it's not the best probably...

Laravel Migration:

class CreateAttachmentsTable extends Migration
{
    public function up()
    {
        Schema::create('attachments', function (Blueprint $table) {
            $table->binary('content');
        });
    }
}

Laravel Controller:

public function upload(Request $request)
{
    $file = new File();
    $file->content = $request->fileContent;
    $file->save();
}

Angular Component:

onFileChange(event) {
    if (event.target.files.length > 0) {
        const reader = new FileReader();

        reader.onload = (e) => {
            this.fileService.upload(reader.result).subscribe();
        };

        reader.readAsDataURL(event.target.files[0]);
    }
}

Angular Service:

saveAttachment(fileContent: File) {
    return this.http.post(API_URL + '/upload, { fileContent: file });
}
查看更多
登录 后发表回答