Upload file from one site collection to another in SPFx
-
08-02-2021 - |
Domanda
I have a SPFx solution which have a input tag to upload a file. When I try to upload the file in the same context of the site collection it works fine, but I am not able to get uploaded to different site collection.
Example: <input type=file"/> is used to upload the file in https://sharepoint.com/sites/test1. When I try to upload using sp.web.getFolderByServerRelativeUrl it works fine within same site collection & file uploaded successfully. But I need to upload the file to https://sharepoint.com/sites/test2. Can anyone please help me with this cross site collection file upload issue?
Soluzione
Sample test demo(React framework):
Note: the user should have permission for target site/library.
<input type="file" id="uploadFile" />
<button className="button" onClick={() => this.UploadFile()} >Upload</button>
Below is the JS code.
protected UploadFile(){
var files = (document.getElementById('uploadFile') as HTMLInputElement).files;
var file = files[0];
if (file != undefined || file != null) {
let spOpts : ISPHttpClientOptions = {
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: file
};
var url = `https://xxx.sharepoint.com/sites/site/_api/Web/Lists/getByTitle('MyDoc')/RootFolder/Files/Add(url='${file.name}', overwrite=true)`
this.props.context.spHttpClient.post(url, SPHttpClient.configurations.v1, spOpts).then((response: SPHttpClientResponse) => {
console.log(`Status code: ${response.status}`);
console.log(`Status text: ${response.statusText}`);
response.json().then((responseJSON: JSON) => {
console.log(responseJSON);
});
});
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange