回顾API从磁盘发送文件

时间:2019-12-03 14:34:06

标签: c# httprequest autodesk-forge

我正在尝试在C#中复制curl请求,以使用Recap API将文件(从磁盘)发送到光幕。

curl -v 'https://developer.api.autodesk.com/photo-to-3d/v1/file' \
-X 'POST' \
-H 'Authorization: Bearer eyjhbGCIOIjIuzI1NiISimtpZCI6...' \
-F "photosceneid=hcYJcrnHUsNSPII9glhVe8lRF6lFXs4NHzGqJ3zdWMU" \
-F "type=image" \
-F "file[0]=@c:/sample_data/_MG_9026.jpg" \
-F "file[1]=@c:/sample_data/_MG_9027.jpg"

到目前为止,我已经在C#中获得了这个

private async Task<string> SendUploadJsonAsync(PhotoSceneImages obj, HttpMethod method, string token)
{
    const string url = "https://developer.api.autodesk.com/photo-to-3d/v1/file";

    using (var client = new HttpClient())
    {
        var formData = new MultipartFormDataContent
        {
            {new StringContent(obj.photosceneid), "photosceneid"}, {new StringContent("type"), "image"}
        };

        var i = 0;
        foreach (var image in obj.files)
        {
            formData.Add(new ByteArrayContent(image), "file["+ i++ +"]");
        }
        var request = new HttpRequestMessage
        {
            Content = formData,
            Headers =
            {
                Authorization = new AuthenticationHeaderValue("Bearer", token)
            },
            Method = method,
            RequestUri = new Uri(url)
        };

        try
        {
            var response = await client.SendAsync(request);
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
}

但是我从Autodesk服务器收到尚未实现的答复。

不知道我做错了什么。

PhotoSceneImages对象包含一个带有photoceneid的字符串和一个包含图像文件字节的字节数组。

1 个答案:

答案 0 :(得分:1)

使其正常工作,

private async Task<string> SendUploadImagesAsync(PhotoSceneImages obj, HttpMethod method, string token)
{
    const string url = "https://developer.api.autodesk.com/photo-to-3d/v1/file";

    using (var client = new HttpClient())
    {
        var formData = new MultipartFormDataContent
        {
            {new StringContent(obj.photosceneid), "photosceneid"}, {new StringContent(obj.type), "type"}
        };

        var i = 0;
        foreach (var file in obj.files)
        {
            formData.Add(new ByteArrayContent(file.byteArray), $"file[{i++}]", file.filename);
        }
        var request = new HttpRequestMessage
        {
            Content = formData,
            Headers =
            {
                Authorization = new AuthenticationHeaderValue("Bearer", token)
            },
            Method = method,
            RequestUri = new Uri(url)
        };
        Debug.Log($"request: {request}");
        try
        {
            var response = await client.SendAsync(request);
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
}

基本上有两个错误,字段(“ type”:“ image”)是我发送错误的方法,您还需要在formData上发送文件名作为第三个参数。