首页 文章

使用来自Java客户端的REST API将附件上载到SharePoint列表项

提问于
浏览
0

以下Java代码是将文件附件上载到SharePoint 2013列表项的示例 .

String uploadquery =siteurl+ _api/web/Lists/GetByTitle('ListName')/items(1)/AttachmentFiles/add(FileName='File1.txt')";

    HttpPost httppost = new HttpPost(uploadquery);
    httppost.addHeader("Accept", "application/json;odata=verbose");
    httppost.addHeader("X-RequestDigest", FormDigestValue);
    httppost.addHeader("X-HTTP-Method", "PUT");
    httppost.addHeader("If-Match", "*");

    StringEntity se = new StringEntity("This is a Body");
    httppost.setEntity(se);
    HttpResponse response = httpClient.execute(httppost, localContext);

它使用content创建文件 . 但它在响应中返回以下错误 .

{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The type SP.File does not support HTTP PATCH method."}}}

是什么导致这个问题?

在上面的代码中,我上传了简单的文本内容 . 但是如何将其他文件类型(如excel / ppt或图像)上传到sharepoint列表项?

2 回答

  • 1

    根据Working with folders and files with REST,必须指定以下属性才能创建列表项的文件附件:

    • POST HTTP请求的方法
      带有 FormDigest 值的

    • X-RequestDigest 标头

    • HTTP请求 bodycontent length

    伪示例:

    url: http://site url/_api/web/lists/getbytitle('list title')/items(item id)/AttachmentFiles/ add(FileName='file name')
    method: POST
    headers:
        Authorization: "Bearer " + accessToken
        body: "Contents of file."
        X-RequestDigest: form digest value
        content-length:length of post body
    

    C#示例

    以下C#示例演示如何使用Network API将创建文件附件上载到列表项到SharePoint Online(SPO):

    var fileName = Path.GetFileName(uploadFilePath);
    var requestUrl = string.Format("{0}/_api/web/Lists/GetByTitle('{1}')/items({2})/AttachmentFiles/add(FileName='{3}')", webUrl, listTitle, itemId,fileName);
    var request = (HttpWebRequest)WebRequest.Create(requestUrl);
    request.Credentials = credentials;  //SharePointOnlineCredentials object 
    request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
    
    request.Method = "POST";
    request.Headers.Add("X-RequestDigest", requestDigest);
    
    var fileContent = System.IO.File.ReadAllBytes(uploadFilePath);
    request.ContentLength = fileContent.Length;
    using (var requestStream = request.GetRequestStream())
    {
        requestStream.Write(fileContent, 0, fileContent.Length);
    }
    
    var response = (HttpWebResponse)request.GetResponse();
    

    我相信只需很少的努力就可以转换成Java版本 .

  • 1

    我使用了以下URL和相关代码为我工作

    https:// [your_domain] .sharepoint.com / _api / web / GetFolderByServerRelativeUrl('/ Shared%20Documents / [FolderName]')/ Files / Add(url ='“[FileName]”',overwrite = true)

    public String putRecordInSharePoint(File file) throws ClientProtocolException, IOException
    {
        /* Token variable declaration */
        String token = getSharePointAccessToken();
        /* Null or fail check */
        if (!token.equalsIgnoreCase(RcConstants.OAUTH_FAIL_MESSAGE))
        {
            /* Upload path and file name declaration */
            String Url_parameter = "Add(url='" + file.getName() + "',overwrite=true)";
            String url = RcConstants.UPLOAD_FOLDER_URL + Url_parameter;
    
    
            /* Building URL */
            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            post.setHeader("Authorization", "Bearer " + token);
            post.setHeader("accept", "application/json;odata=verbose");
            /* Declaring File Entity */
            post.setEntity(new FileEntity(file));
    
            /* Executing the post request */
            HttpResponse response = client.execute(post);
            logger.debug("Response Code : " + response.getStatusLine().getStatusCode());
    
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()
                    || response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value())
            {
                /* Returning Success Message */
                return RcConstants.UPLOAD_SUCCESS_MESSAGE;
            }
            else
            {
                /* Returning Failure Message */
                return RcConstants.UPLOAD_FAIL_MESSAGE;
            }
        }
        return token;
    }
    

相关问题