将b64图片上传到imgur

时间:2019-03-23 08:42:49

标签: angular typescript imgur

我正在尝试将b64图片(https://pastebin.com/1ereVVqh)上传到imgur,并不断出现以下错误:

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: "https://api.imgur.com/3/image", ok: false, …}
error:
data: {error: "Invalid URL (data:image/jpeg;base64,/9j/4AAQSkZJRg…CGmGI2nNxt/MW7l/qMleILRMoczAlq57S8Ia6HQg3UY5Z//Z)", request: "/3/image", method: "POST"}
status: 400
success: false
__proto__: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for https://api.imgur.com/3/image: 400 OK"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "OK"
url: "https://api.imgur.com/3/image"
__proto__: HttpResponseBase

我的代码如下:

upload.controller.ts

  handleFileInput(e) {
    const reader = new FileReader();
    if (e.target.files && e.target.files.length) {
      const [file] = e.target.files;
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.imgurService.upload(reader.result, this.user.uid).subscribe((imgurResponse: ImgurResponse) => {
          this.logger.debug(imgurResponse);
        });
      };
    }
  }

imgur.service.ts

  upload(base64Img: any, uid: string) {
    this.logger.debug('Handling file input');
    this.logger.debug(base64Img);
    this.logger.debug(`Uploading picture to ${this.IMGUR_UPLOAD_URL}`);
    const headers = new HttpHeaders().set('Authorization', `${this.IMGUR_CLIENT_ID}`);
    const formData = new FormData();
    formData.append('image', base64Img);
    formData.append('name', uid);
    formData.append('type', 'file');
    return this.http.post<ImgurResponse>(`${this.IMGUR_UPLOAD_URL}`, formData, { headers });
  }

知道为什么它不起作用吗?

1 个答案:

答案 0 :(得分:1)

根据imgur API文档,在您的情况下,类型应设置为base64: (甚至可能是base64编码的URI的URL,您需要尝试使用哪一个)

Image Upload
Upload a new image.

Method  POST
Route   https://api.imgur.com/3/image
Alternative Route   https://api.imgur.com/3/upload
Response Model  Basic
Parameters
Key Required    Description
image   required    A binary file, base64 data, or a URL for an image. (up to 10MB)
album   optional    The id of the album you want to add the image to. For anonymous albums, {album} should be the deletehash that is returned at creation.
type    optional    The type of the file that's being sent; file, base64 or URL
name    optional    The name of the file, this is automatically detected if uploading a file with a POST and multipart / form-data
title   optional    The title of the image.
description optional    The description of the image.