【问题标题】:upload attachment to SharePoint List Item using REST API from Java client使用 Java 客户端中的 REST API 将附件上传到 SharePoint 列表项
【发布时间】:2014-10-05 08:14:09
【问题描述】:

以下 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);

它使用内容创建文件。但它在响应中返回以下错误。

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

是什么导致了这个问题?

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

【问题讨论】:

    标签: java rest http sharepoint sharepoint-2013


    【解决方案1】:

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

    • POST HTTP 请求方法
    • X-RequestDigest 带有 FormDigest 值的标头
    • 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 版本。

    【讨论】:

    • 什么是 requestDigest?
    • 请求摘要可以从yoursite/_api/context获取。我想你必须向上面的 api 发出另一个 http 请求,获取摘要并与 post 请求一起发送
    【解决方案2】:

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

    https://[your_domain].sharepoint.com/_api/web/GetFolderByServerRelativeUrl('/Shared%20Documents/[FolderName]')/Files/Add(url='" + [文件名] + "',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;
    }
    

    【讨论】:

    • 我能够得到请求,但你能给我适当的样本,我可以用于 [FileName] 。我收到错误 403(仅用于上传调用)并响应 System.Runtime.InteropServices.COMException“此页面的安全验证无效。在您的 Web 浏览器中单击返回....”提前致谢
    • 我有以下来自 POC 的示例,请随意查看。 github.com/nikhiln64/Java-REST-API-Projects/tree/master/…
    • 使用任何 pdf/doc/其他类型的文件,您必须更改文件名如下: /Files/Add(url='file1.pdf', overwrite=true) 最初尝试使用 Postman那么最终你会弄明白的。
    • 非常感谢!我现在就试试:)
    猜你喜欢
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多