【发布时间】:2020-05-30 07:31:33
【问题描述】:
我也在尝试通过 API 使用 C# 上传文件。
StreamUtils 不起作用,我收到错误消息:“无法将 lambda 表达式转换为类型‘字符串’,因为它不是委托类型”。
知道如何上传文件吗? 大约 100MB。
public void UploadModel(string ProjectId, string filename, Stream fileStream)
{
string access_token_string = Read_Json_Values("access_token");
string webstring = String.Format("https://api.test.com/v2/projects/{0}/revisions", ProjectId);
var client = new RestClient(webstring);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + access_token_string);
request.AddHeader("Content-Type", "application/ifc");
request.AddHeader("xxx-Params", "{\"callbackUri\": \"https://example.com\", \"filename\": \"mk337.ifc\", \"comment\": \"From Postman\", \"model\": \"21312312312312\"}");
request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename);
IRestResponse response = client.Execute(request);
Console.WriteLine("Model is uploaded!");
}
internal static class StreamUtils
{
private const int STREAM_BUFFER_SIZE = 128 * 1024; // 128KB
public static void CopyStream(Stream source, Stream target)
{ CopyStream(source, target, new byte[STREAM_BUFFER_SIZE]); }
public static void CopyStream(Stream source, Stream target, byte[] buffer)
{
if (source == null) throw new ArgumentNullException("source");
if (target == null) throw new ArgumentNullException("target");
if (buffer == null) buffer = new byte[STREAM_BUFFER_SIZE];
int bufferLength = buffer.Length;
int bytesRead = 0;
while ((bytesRead = source.Read(buffer, 0, bufferLength)) > 0)
target.Write(buffer, 0, bytesRead);
}
【问题讨论】:
-
我可以假设这一行
request.AddFile("file",s=>StreamUtils.CopyStream(fileStream, s), filename);抛出异常,但需要澄清。 -
行 request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename) 导致问题,因为 "s => StreamUtils.CopyStream(fileStream, s)"是一个 lambda 表达式,而不是一个流。您要做的就是在函数 StreamUtils.CopyStream(Stream source, Stream target) 中按预期定义一个目标 Stream
-
您对
request.AddFile()的调用似乎与任何可用的方法签名都不匹配:see this link for clarification。 -
这有帮助吗?它提供了如何使用 RestSharp stackoverflow.com/questions/32876606/… 上传文件的答案
-
@rekcul 嘿,你能提供一个示例代码吗?