Contentful Management API上传图片

时间:2018-06-01 18:53:39

标签: contentful contentful-management

我直接使用CMA(没有SDK)。我正在尝试将文件上传到Contenful。从我读过的内容来看,这就是:

  1. 上传文件
  2. 创建资产(将其与最近上传的文件相关联)
  3. 处理资产
  4. 我上传的文件如下:

    const xhr: XMLHttpRequest = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200 || xhr.status === 201) {
          let data: any = JSON.parse(xhr.response);
          resolve(JSON.parse(xhr.response));
        } else {
          reject(xhr.response);
        }
      }
    };
    
    const url = "https://upload.contentful.com/spaces/" + space_id + "/uploads";
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/octet-stream");
    xhr.setRequestHeader("Authorization", "Bearer " + token);
    const formData = new FormData();
    formData.append("file", file, file.name);
    xhr.send(formData);
    

    然后我创建这样的资产:

    const request = {
    fields: {
      file: {
        "en-US": {
          contentType: file.type,
          fileName: file.name,
          uploadFrom: {
            sys: {
              type: "Link",
              linkType: "Upload",
              id: uploadId
            }
          }
        }
      }
    }
    

    };

     return axios
        .post(
          "https://api.contentful.com/spaces/" + space_id + "/assets",
          JSON.stringify(request),
          config
        )....
    

    然后像这样处理:

     const request = {
    fields: {      
     file: {
        "en-US": {
          contentType: "image/png",
          fileName: "Sample_45.png",
          uploadFrom: {
            sys: {
              linkType: "Upload",
              type: "Link",
              id:uploadId
            }
          }
        }
      }
    }
    

    };

     return axios
        .put(
          "https://api.contentful.com/spaces/" +
            space_id +
            "/assets/" +
            assetId +
            "/files/en-US/process",
            asset.data.fields,
          config
        )
    

    之后我可以在Contentful Media中看到资产,但图像从未真正加载,也不会显示图像大小。似乎Contenful如何识别文件,或者与资产错误关联;我没有线索。请帮助。

1 个答案:

答案 0 :(得分:0)

看起来你正在使用React。

创建上传表单:

<input type="file" onChange={this.fileChangedHandler}>
<button onClick={this.uploadHandler}>Upload!</button>

并设置statefileChangedHandleruploadHandler

state = {selectedFile: null}

fileChangedHandler = (event) => {
  this.setState({selectedFile: event.target.files[0]})
}

uploadHandler = () => { 
  axios.post(
    'https://upload.contentful.com/spaces/{space_id}/uploads, 
    this.state.selectedFile, 
    config
  )
}

上传完成后,您可以创建,处理和发布资产。