使用office365-rest-api上传含%的文件到SharePoint出现转义问题如何解决
问题原因
%是URL编码中的特殊字符,本身的URL编码结果为%25。你使用的Office 365 REST Python SDK的upload_file方法内部会自动对传入的文件名做URL编码,当文件名本身包含%时,编码后的结果就会出现%25,最终在SharePoint中显示为异常的文件名。
解决方案
方案1:改用不会自动编码的files.add方法(更稳定,优先推荐)
直接调用文件夹对象的files.add方法上传文件,该方法不会额外对文件名做URL编码,修改后的代码如下:
from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.user_credential import UserCredential ctx=ClientContext('https://mycomp.sharepoint.com/sites/MySite/').with_credentials(userCredentials) SP_Location="TheLibrary/TheFolder" fileName="First 50% of Candidates.xls" path="../../path/First 50% of Candidates.xls" with open(path, 'rb') as content_file: fileContent=content_file.read() targetFolder=ctx.web.ensure_folder_path(SP_Location).execute_query() # 替换原有upload_file方法,overwrite参数指定是否覆盖同名文件 targetFile=targetFolder.files.add(fileName, fileContent, overwrite=True) ctx.execute_query()
方案2:适配原有upload_file逻辑
如果要继续使用upload_file方法,可以在传入文件名前先对其做一次URL解码,抵消方法内部自动编码的影响,示例代码如下:
import urllib.parse # 其余原有代码不变 fileName="First 50% of Candidates.xls" # 提前解码一次,抵消upload_file的自动编码操作 processed_fileName = urllib.parse.unquote(fileName) targetFile=targetFolderUrl.upload_file(processed_fileName,fileContent)
验证注意事项
修改代码后可以测试带%、&、#等特殊字符的文件名上传,确认SharePoint端显示的文件名和本地文件名完全一致。
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

