我的目标是 GET 和 POST 文件到 SP Online。
我已经用这两种方法编写了一个 WEB API。这些方法使用 CSOM 与 SP Online 交互。
GET 向客户端返回响应 Ok(字节数组),POST 获取要在请求正文中上传的整个文件,并分块执行上传到 Sharepoint Online。
有人告诉我应该使用流技术,因为上下文是具有许多并发请求的企业应用程序。因此 GET 方法应该向客户端返回一个流,而客户端应该将请求作为一个流发送到 POST。
在客户端,我不得不使用 RestSharp 库。
所以:
1)如何使用RestSharp处理流?
2) WebAPI 如何返回流?
3) 除了文件,我还发送了很多元数据。如何以流模式上传文件并仅发送一次元数据?
客户端,get 需要字节数组,post 发送字节数组和元数据。
在网上我发现了太多技巧。有标准的吗?
请您参考如下方法:
有一个非常基本的例子。它没有涵盖您的所有问题,但这是一个起点。
使用 RestSharp 的客户端:
(我做了一个小的 ASP.NET Core 2.0 控制台应用程序)。将以下代码添加到您的 Programm.cs)
using System;
using System.IO;
using RestSharp;
namespace RestSharpClient
{
class Program
{
public const string baseUrl = "http://localhost:58610/api/values"; // <-- Change URL to yours!
static void Main(string[] args)
{
Console.ReadKey();
string tempFile = Path.GetTempFileName();
using (var writer = File.OpenWrite(tempFile))
{
var client = new RestClient(baseUrl);
var request = new RestRequest();
request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer);
var response = client.DownloadData(request);
}
Console.ReadKey();
}
}
}
服务器
我的 Controller :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
namespace Server.Controllers { [Route("api/[controller]")]
public class ValuesController: Controller {
// GET api/values
[HttpGet]
public FileStreamResult GetTest() {
var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World"));
return new FileStreamResult(stream, new MediaTypeHeaderValue("text/plain")) {
FileDownloadName = "test.txt"
};
}
}
}
重要提示:启用 CORS。为此,将以下行添加到您的 Startup.cs 之前的 services.AddMvc();
services.AddCors();
如何添加元数据:
WebAPI method that takes a file upload and additional arguments
