0

我直接使用 CMA(没有 SDK)。我正在尝试将文件上传到 Contentful。从我读到的流程是这样的:

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

我正在上传这样的文件:

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 无法识别文件,或者与资产的关联不正确;我没有线索。请帮忙。

4

1 回答 1

0

看起来你正在使用 React。

创建一个上传表单:

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

并设置您的state,fileChangedHandleruploadHandler:

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

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

于 2018-06-01T22:31:23.500 回答