HTTP客户端上传文件C#

发布于 2025-01-11 09:02:24 字数 3227 浏览 0 评论 0原文

这是下面的代码(C#)要在 https://nft.storage/ 中上传它工作正常但是当我上传mp4文件(上传成功),上传的文件不起作用。源代码 https://github.com/filipepolizel/unity-nft-storage 我使用了许多不同的 HTTPCLIENT 示例,但它是相同的 损坏的上传 mp4 文件: http://ipfs.io/ipfs/bafybeibt4jqvncw6cuyih27mujbpdmsjl46pykablvravh3qg63vuvcdqy

// nft.storage API endpoint
        private static readonly string nftStorageApiUrl = "https://api.nft.storage/";

        // HTTP client to communicate with nft.storage
        private static readonly HttpClient nftClient = new HttpClient();

        // http client to communicate with IPFS API
        private static readonly HttpClient ipfsClient = new HttpClient();

        // nft.storage API key
        public string apiToken;

void Start()
        {
            nftClient.DefaultRequestHeaders.Add("Accept", "application/json");
            if (apiToken != null)
            {
                nftClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + apiToken);
            }
            else
            {
                // log in console in case no API key is found during initialization
                Debug.Log("Starting NFT Storage Client without API key, please call 'SetApiToken' method before using class methods.");
            }
        }

public async Task<NFTStorageUploadResponse> UploadDataFromFile(string path)
        {
            StreamReader reader = new StreamReader(path);
            string data = reader.ReadToEnd();
            reader.Close();
            print("Uploading...");
            return await UploadDataFromString(data);
        }


public async Task<NFTStorageUploadResponse> UploadDataFromString(string data)
        {
            string requestUri = nftStorageApiUrl + "/upload";
            string rawResponse = await Upload(requestUri, data);
            NFTStorageUploadResponse parsedResponse = JsonUtility.FromJson<NFTStorageUploadResponse>(rawResponse);
            return parsedResponse;
        }

private async Task<string> Upload(string uri, string paramString)
        {
            try
            {
                using (HttpContent content = new StringContent(paramString))
                {
                    //content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    content.Headers.ContentType = new MediaTypeHeaderValue("*/*");
                    HttpResponseMessage response = await nftClient.PostAsync(uri, content);
                    response.EnsureSuccessStatusCode();
                    Stream responseStream = await response.Content.ReadAsStreamAsync();
                    StreamReader reader = new StreamReader(responseStream);
                    return reader.ReadToEnd();
                }
            }
            catch (HttpRequestException e)
            {
                Debug.Log("HTTP Request Exception: " + e.Message);
                Debug.Log(e);
                return null;
            }
        }

This is the code below (C#) To upload in https://nft.storage/ It Works fine But when I upload mp4 file (Uploaded successfully) , The uploaded file doesn’t work . Source Code https://github.com/filipepolizel/unity-nft-storage
I used many different HTTPCLIENT example but it same
broken Uploaded mp4 File: http://ipfs.io/ipfs/bafybeibt4jqvncw6cuyih27mujbpdmsjl46pykablvravh3qg63vuvcdqy

// nft.storage API endpoint
        private static readonly string nftStorageApiUrl = "https://api.nft.storage/";

        // HTTP client to communicate with nft.storage
        private static readonly HttpClient nftClient = new HttpClient();

        // http client to communicate with IPFS API
        private static readonly HttpClient ipfsClient = new HttpClient();

        // nft.storage API key
        public string apiToken;

void Start()
        {
            nftClient.DefaultRequestHeaders.Add("Accept", "application/json");
            if (apiToken != null)
            {
                nftClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + apiToken);
            }
            else
            {
                // log in console in case no API key is found during initialization
                Debug.Log("Starting NFT Storage Client without API key, please call 'SetApiToken' method before using class methods.");
            }
        }

public async Task<NFTStorageUploadResponse> UploadDataFromFile(string path)
        {
            StreamReader reader = new StreamReader(path);
            string data = reader.ReadToEnd();
            reader.Close();
            print("Uploading...");
            return await UploadDataFromString(data);
        }


public async Task<NFTStorageUploadResponse> UploadDataFromString(string data)
        {
            string requestUri = nftStorageApiUrl + "/upload";
            string rawResponse = await Upload(requestUri, data);
            NFTStorageUploadResponse parsedResponse = JsonUtility.FromJson<NFTStorageUploadResponse>(rawResponse);
            return parsedResponse;
        }

private async Task<string> Upload(string uri, string paramString)
        {
            try
            {
                using (HttpContent content = new StringContent(paramString))
                {
                    //content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    content.Headers.ContentType = new MediaTypeHeaderValue("*/*");
                    HttpResponseMessage response = await nftClient.PostAsync(uri, content);
                    response.EnsureSuccessStatusCode();
                    Stream responseStream = await response.Content.ReadAsStreamAsync();
                    StreamReader reader = new StreamReader(responseStream);
                    return reader.ReadToEnd();
                }
            }
            catch (HttpRequestException e)
            {
                Debug.Log("HTTP Request Exception: " + e.Message);
                Debug.Log(e);
                return null;
            }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

捎一片雪花 2025-01-18 09:02:24

答案对我有帮助。谢谢,我将上传方法更改为:

public static async Task<string> Upload(string uri, string pathFile)
    {

        byte[] bytes = System.IO.File.ReadAllBytes(pathFile);

        using (var content = new ByteArrayContent(bytes))
        {
            content.Headers.ContentType = new MediaTypeHeaderValue("*/*");

            //Send it
            var response = await nftClient.PostAsync(uri, content);
            response.EnsureSuccessStatusCode();
            Stream responseStream = await response.Content.ReadAsStreamAsync();
            StreamReader reader = new StreamReader(responseStream);
            return reader.ReadToEnd();
        }
    }

现在效果很好

the answer helped me . thanks , I changed the Upload method to :

public static async Task<string> Upload(string uri, string pathFile)
    {

        byte[] bytes = System.IO.File.ReadAllBytes(pathFile);

        using (var content = new ByteArrayContent(bytes))
        {
            content.Headers.ContentType = new MediaTypeHeaderValue("*/*");

            //Send it
            var response = await nftClient.PostAsync(uri, content);
            response.EnsureSuccessStatusCode();
            Stream responseStream = await response.Content.ReadAsStreamAsync();
            StreamReader reader = new StreamReader(responseStream);
            return reader.ReadToEnd();
        }
    }

It works great now

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文