为了账号安全,请及时绑定邮箱和手机立即绑定

上传json图片发送api请求

上传json图片发送api请求

红颜莎娜 2023-12-14 14:34:16
我想将图像作为 json 发送到 post api,但是当我以 json 形式发送图像的 url 时,响应显示错误。但是在邮递员中,当我通过文件上传发送图像时,它可以工作。我的json:{name:"xxx",image:"someurl"}我的 C# 代码: {            string url = "xxxxxxxxxx";            HttpWebRequest webRequest = null;            HttpWebResponse webResponse = null;            string responseFromServer = "";            webRequest = (HttpWebRequest)WebRequest.Create(url);            webRequest.Credentials = CredentialCache.DefaultCredentials;            webRequest.ContentType = "application/json";                       webRequest.Method = "POST";            webRequest.ReadWriteTimeout = 300000;            // Get the response.            using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))            {                streamWriter.Write(jsonREQ);                streamWriter.Flush();                streamWriter.Close();            }            using (webResponse = (HttpWebResponse)webRequest.GetResponse())            {                Stream responseStream = webResponse.GetResponseStream();                using (StreamReader sr = new StreamReader(responseStream))                {                    responseFromServer = sr.ReadToEnd();                    sr.Close();                }                webResponse.Close();            }            return responseFromServer;        }这里的 json 请求有 json,当我使用这个时,我没有得到预期的响应,但是当我使用 postman 进行文件上传时, 它可以工作,请建议我一种以 json 发送图像的方法。(* 已尝试过 base64 和 byte ,它没有按预期工作*)
查看完整描述

1 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

尝试这个:


var formData = new FormData();

formData.append("image", fileInputElement.files[0]);


var request = new XMLHttpRequest();

request.open("POST", "http://example.com/submitform.php");

request.send(formData);

并在服务器上将其上传到另一台服务器:


string responseString;


using (var fileStream = new FileStream(filePath, FileMode.Open))

{

    var formData = new MultipartFormDataContent {

        { new StreamContent(fileStream), @"image", Path.GetFileName(filePath) }

    };


    var request = (HttpWebRequest)WebRequest.Create("URL");

    request.Method = WebRequestMethods.Http.Post;


    request.AllowWriteStreamBuffering = false;

    request.SendChunked = true; // set to true to avoid exception when AllowWriteStreamBuffering = false and ContentLength is not set

    request.Headers.Add("abc", "def");


    request.ContentType = formData.Headers.ContentType.ToString();


    try

    {

        // Get the request stream with the default timeout

        using (Stream requestStream = await request.GetRequestStreamAsyncWithTimeout())

        {

            // Upload the file with no timeout

            await formData.CopyToAsync(requestStream);

        }


        // Get response with the default timeout, and parse the response body

        using (WebResponse response = await request.GetResponseAsyncWithTimeout())

        using (Stream responseStream = response.GetResponseStream())

        using (StreamReader reader = new StreamReader(responseStream))

        {

            responseString = reader.ReadToEnd();

        }

    }

    catch (WebException ex)

    {

        if (ex.Status == WebExceptionStatus.Timeout)

        {

            throw new TimeoutException("Timeout while uploading file.", ex);

        }

        throw;

    }

}

ResultModel result = JsonConvert.DeserializeObject<ResultModel>(responseString);

这些扩展可以让您的上传请求在文件较大或连接速度较慢时不会超时:


public static class WebRequestExtensions

{

    public static async Task<Stream> GetRequestStreamAsyncWithTimeout(this WebRequest request, int? millisecondsTimeout = null)

    {

        Task<Stream> getTask = request.GetRequestStreamAsync();


        if (await Task.WhenAny(getTask, Task.Delay(request.Timeout)) == getTask)

        {

            // task completed without timeout

            return getTask.Result;

        }

        else

        {

            // timeout

            var ex = new TimeoutException();

            throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);

        }

    }


    public static async Task<WebResponse> GetResponseAsyncWithTimeout(this WebRequest request, int? millisecondsTimeout = null)

    {

        Task<WebResponse> getTask = request.GetResponseAsync();


        if (await Task.WhenAny(getTask, Task.Delay(request.Timeout)) == getTask)

        {

            // task completed without timeout

            return getTask.Result;

        }

        else

        {

            // timeout

            var ex = new TimeoutException();

            throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);

        }

    }


    private static T AsyncToSyncWithTimeout<T>(

        Func<AsyncCallback, object, IAsyncResult> begin,

        Func<IAsyncResult, T> end,

        int millisecondsTimeout)

    {

        var iar = begin(null, null);

        if (!iar.AsyncWaitHandle.WaitOne(millisecondsTimeout))

        {

            var ex = new TimeoutException();

            throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);

        }

        return end(iar);

    }

}


查看完整回答
反对 回复 2023-12-14
  • 1 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信