src/util/sp/uploadListItemFile.js
import readFileToString from '../readFileToString';
import respToJson from '../respToJson';
/**
* Upload file as attachment to a list item.
*
* @param {string} list Name of list.
* @param {string} id Id of item.
* @param {File} file File object from upload.
* @return {Promise}
*/
export default function uploadListItemFile(list, id, file) {
const siteurl = window._spPageContextInfo.webServerRelativeUrl;
const urlTemplate = `${siteurl}/_api/web/lists/getByTitle('${list}')/items(${id})/AttachmentFiles/add(FileName='${file.name}')`;
const requestDigest = document.getElementById('__REQUESTDIGEST');
return readFileToString(file)
.then((filedata) => {
return fetch(urlTemplate, {
credentials: 'same-origin',
method: 'POST',
headers: {
'Accept': 'application/json;odata=verbose',
'Content-Type': 'application/json;odata=verbose',
'Content-Length': filedata.length,
'X-RequestDigest': requestDigest && requestDigest.value || '',
'binaryStringRequestBody': 'true',
},
body: filedata,
});
})
.then(respToJson);
}