在SPFX Web部件中使用SPHttpClient将文件上传到SharePoint Online [英] Upload files to SharePoint Online using SPHttpClient in an spfx webpart
问题描述
我正在尝试在spfx Webpart中使用SPHttpClient上传文件.
I'm trying to upload a file using SPHttpClient in a spfx webpart.
我正在尝试的代码是
const spOpts:ISPHttpClientOptions={body: { my: "bodyJson" } };
contextDetails.spHttpClient.post(url,SPHttpClient.configurations.v1, spOpts)
.then(response => {
return response;
})
.then(json => {
return json;
}) as Promise<any>
但是我不确定如何将文件内容添加到此httpClient API.
But I'm not sure how to add content of the file to this httpClient API.
我想我们必须在body参数中将文件内容添加到spOpts中.不过我不确定.
I guess we have to add content of file to spOpts in body parameter. I'm not sure though.
感谢您的帮助. 谢谢.
Any help is appreciated. Thanks.
推荐答案
假设您正在使用并输入文件标签,如下所示:
Assuming that you are using and input file tag as below:
<input type="file" id="uploadFile" value="Upload File" />
<input type="button" class="uploadButton" value="Upload" />
然后您可以按如下所示注册uploadButton的处理程序:
You can then register the handler of the uploadButton as below:
private setButtonsEventHandlers(): void {
this.domElement.getElementsByClassName('uploadButton')[0].
addEventListener('click', () => { this.UploadFiles(); });
}
现在,在UploadFiles
方法中,您可以添加文件的内容和其他必要的标题.另外,假设您要将文件上传到文档库,则可以使用以下代码片段将文件上传到该文件库.根据您的网站网址和文档库名称进行修改:
Now, in the UploadFiles
method, you can add the file's content and other necessary headers. Also, assuming that you are uploading the file to a document library, you can use the below snippet to upload a file to it. Modify it as per your site url and doc lib name:
var files = (<HTMLInputElement>document.getElementById('uploadFile')).files;
//in case of multiple files,iterate or else upload the first file.
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://<your-site-url>/_api/Web/Lists/getByTitle('Documents')/RootFolder/Files/Add(url='${file.name}', overwrite=true)`
this.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);
});
});
}
这篇关于在SPFX Web部件中使用SPHttpClient将文件上传到SharePoint Online的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!