I'm using the CMA directly (no SDK). I am trying to upload a file to Contenful. From what I've read the flow is this:
I am uploading the file like this:
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);
Then I create the asset like this:
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
)....
and then process it like this:
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
)
After that I can see an asset in Contentful Media, but the image never really loads, nor the image size is displayed. It seems like some how Contenful does not recognize the file, or has been incorrectly associated with the asset; I have no clue. Help please.
Looks like you are using React.
Create an upload form :
<input type="file" onChange={this.fileChangedHandler}>
<button onClick={this.uploadHandler}>Upload!</button>
and set your state
, fileChangedHandler
, and uploadHandler
:
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
)
}
And once the upload is finished, you can create, process, and publish the asset.