猿问

上传json图片发送api请求

我想将图像作为 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 ,它没有按预期工作*)


红颜莎娜
浏览 126回答 1
1回答

一只斗牛犬

尝试这个: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)){&nbsp; &nbsp; var formData = new MultipartFormDataContent {&nbsp; &nbsp; &nbsp; &nbsp; { new StreamContent(fileStream), @"image", Path.GetFileName(filePath) }&nbsp; &nbsp; };&nbsp; &nbsp; var request = (HttpWebRequest)WebRequest.Create("URL");&nbsp; &nbsp; request.Method = WebRequestMethods.Http.Post;&nbsp; &nbsp; request.AllowWriteStreamBuffering = false;&nbsp; &nbsp; request.SendChunked = true; // set to true to avoid exception when AllowWriteStreamBuffering = false and ContentLength is not set&nbsp; &nbsp; request.Headers.Add("abc", "def");&nbsp; &nbsp; request.ContentType = formData.Headers.ContentType.ToString();&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Get the request stream with the default timeout&nbsp; &nbsp; &nbsp; &nbsp; using (Stream requestStream = await request.GetRequestStreamAsyncWithTimeout())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Upload the file with no timeout&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; await formData.CopyToAsync(requestStream);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Get response with the default timeout, and parse the response body&nbsp; &nbsp; &nbsp; &nbsp; using (WebResponse response = await request.GetResponseAsyncWithTimeout())&nbsp; &nbsp; &nbsp; &nbsp; using (Stream responseStream = response.GetResponseStream())&nbsp; &nbsp; &nbsp; &nbsp; using (StreamReader reader = new StreamReader(responseStream))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; responseString = reader.ReadToEnd();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; catch (WebException ex)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (ex.Status == WebExceptionStatus.Timeout)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new TimeoutException("Timeout while uploading file.", ex);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; throw;&nbsp; &nbsp; }}ResultModel result = JsonConvert.DeserializeObject<ResultModel>(responseString);这些扩展可以让您的上传请求在文件较大或连接速度较慢时不会超时:public static class WebRequestExtensions{&nbsp; &nbsp; public static async Task<Stream> GetRequestStreamAsyncWithTimeout(this WebRequest request, int? millisecondsTimeout = null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Task<Stream> getTask = request.GetRequestStreamAsync();&nbsp; &nbsp; &nbsp; &nbsp; if (await Task.WhenAny(getTask, Task.Delay(request.Timeout)) == getTask)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // task completed without timeout&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return getTask.Result;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // timeout&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var ex = new TimeoutException();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static async Task<WebResponse> GetResponseAsyncWithTimeout(this WebRequest request, int? millisecondsTimeout = null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Task<WebResponse> getTask = request.GetResponseAsync();&nbsp; &nbsp; &nbsp; &nbsp; if (await Task.WhenAny(getTask, Task.Delay(request.Timeout)) == getTask)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // task completed without timeout&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return getTask.Result;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // timeout&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var ex = new TimeoutException();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; private static T AsyncToSyncWithTimeout<T>(&nbsp; &nbsp; &nbsp; &nbsp; Func<AsyncCallback, object, IAsyncResult> begin,&nbsp; &nbsp; &nbsp; &nbsp; Func<IAsyncResult, T> end,&nbsp; &nbsp; &nbsp; &nbsp; int millisecondsTimeout)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var iar = begin(null, null);&nbsp; &nbsp; &nbsp; &nbsp; if (!iar.AsyncWaitHandle.WaitOne(millisecondsTimeout))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var ex = new TimeoutException();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return end(iar);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答