首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >内容管理API上传映像

内容管理API上传映像
EN

Stack Overflow用户
提问于 2018-06-02 02:53:39
回答 1查看 658关注 0票数 0

我直接使用CMA (没有SDK)。我正在尝试上传一个文件到Contenful。据我所知,这个流程是这样的:

  1. Upload
  2. 创建资产(将其与最近上载的文件关联)
  3. Process

asset

我上传的文件是这样的:

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无法识别文件,或者错误地与资产关联;我不知道。请帮帮忙。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-02 06:31:24

看起来你正在使用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
  )
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50649523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档