首页 > 解决方案 > 将文件 multipartformdata 上传到 Hubspot api

问题描述

我正在尝试将文件上传到 hubspot api。 https://developers.hubspot.com/docs/methods/files/post_files 当我查看 CRM 时,一切看起来都很好,除了一些文件名看起来很奇怪。

在此处输入图像描述

文件被创建并获得文件大小但接缝损坏导致我无法打开或下载它们。

我的方法看起来像这样

   private async Task<HsCreateFileResponse> UploadAttachment(string pStream, string pFilename)
    {
        string url = API_BASE_URL + "filemanager/api/v2/files?hapikey=" + API_KEY;
        string path = @"C:\Temp filer\";
        HttpClient client = new HttpClient();
        var content = new MultipartFormDataContent();
        content.Headers.Add("hidden", "true");

        using (var s = new MemoryStream())
        {
            using (var writer = new StreamWriter(s))
            {
                writer.Write(pStream);
                s.Position = 0;
                using (var fs = new FileStream(path + pFilename, FileMode.Create))
                {
                    s.CopyTo(fs);
                }
                writer.Flush();
            }
        }
        using (var fs = new FileStream(path + pFilename, FileMode.Open, FileAccess.Read))
        {
            byte[] bytes = new byte[fs.Length];
            int numBytesToRead = (int)fs.Length;
            int numBytesRead = 0;

            while (numBytesToRead > 0)
            {
                int n = fs.Read(bytes, numBytesRead, numBytesToRead);
                if (n == 0)
                {
                    break;
                }
                numBytesRead += n;
                numBytesToRead -= n;
            }

            numBytesToRead = bytes.Length;
            System.Threading.Thread.Sleep(100);
            content.Add(new StreamContent(new MemoryStream(bytes)), "files", pFilename);
            var res = await client.PostAsync(url, content);
            return JsonConvert.DeserializeObject<HsCreateFileResponse>(await res.Content.ReadAsStringAsync());
        }

    }

标签: c#resthubspot

解决方案


将此添加到内容中:

content.Add(new StringContent("my-folder/and-subfolder"), "folder_paths");
content.Add(new StringContent("my-file-name.png"), "file_names");

推荐阅读