从Java客户端使用REST API将附件上传到SharePoint列表项

问题描述 投票:0回答:2

以下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
2个回答
1
投票

根据使用REST处理文件夹和文件,必须指定以下属性来创建列表项的文件附件:

  • HTTP请求的POST方法
  • 具有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#示例演示了如何使用网络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
投票

我已使用以下网址和以下相关代码为我工作

https:// [您的域] .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;
}
© www.soinside.com 2019 - 2024. All rights reserved.