本文介绍了将图像上传到REST API的问题.. !!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在尝试将图片上传到restApi,但它会引发内部服务器错误。 请考虑我的代码并指导我在哪里找不到的东西 public void UploadAsset( string sToken, string sImage) { string sRes = string .Empty; Uri地址= new Uri( https://services-sandbox.sheerid.com/rest/0.5/asset); // 创建网络请求 HttpWebRequest oHttpWebRequest = WebRequest .Create(address) as HttpWebRequest; oHttpWebRequest.Credentials = new NetworkCredential( mrinalkumarjha, ******); oHttpWebRequest.Headers [ 授权] = Bearer 624a3eef46f79772958693fa87118b29; oHttpWebRequest.Method = POST; oHttpWebRequest.ContentType = multipart / form-data; // 创建我们要发送的数据 string sFile = asset.png; StringBuilder data = new StringBuilder(); data.Append( file = + HttpUtility.UrlEncode(@sFile)); data.Append( & failure = + HttpUtility.UrlEncode( 您的网址)); data.Append( & succes = + HttpUtility.UrlEncode( 您的网址)); data.Append( & token = + HttpUtility.UrlEncode(txtToken.Text )); // 创建我们要发送的数据的字节数组 byte [] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); // 在请求标题中设置内容长度 oHttpWebRequest.ContentLength = byteData.Length; // 写入数据。 使用(Stream postStream = oHttpWebRequest.GetRequestStream()) { postStream.Write(byteData, 0 ,byteData.Length); } // 获取回复 (HttpWebResponse响应= oHttpWebRequest.GetResponse() HttpWebResponse) { // 获取响应流 StreamReader reader = new StreamReader(response.GetResponseStream()); // 控制台应用程序输出 sRes = reader.ReadToEnd (); } } 已添加代码块[/ Edit] 解决方案 我已经解决了..在类文件中添加以下内容。 private static readonly编码encoding = Encoding.UTF8; 公共静态HttpWebResponse MultipartFormDataPost(串postUrl,串的userAgent,字典<字符串> postParameters) { 串formDataBoundary =的String.Format( - --------- {0:N},Guid.NewGuid()); string contentType =multipart / form-data; boundary =+ formDataBoundary; byte [] formData = GetMultipartFormData(postParameters,formDataBoundary); 返回PostForm(postUrl,userAgent,contentType, formData); } private static HttpWebResponse PostForm(string postUrl,string userAgent,string contentType,byte [] formData) { HttpWebRequest request = WebRequest.Create(postUrl)as HttpWebRequ est; if(request == null) { 抛出新的NullReferenceException(请求不是一个http请求); } //设置请求属性。 request.Method =POST; request.ContentType = contentType; request.UserAgent = userAgent; request.CookieContainer = new CookieContainer(); request.ContentLength = formData.Length; request.Credentials = new NetworkCredential(mrinalkumarjha,***** ); request.Headers [Authorization] =Bearer 624a3eef46f79772958693fa87118b29; //你也可以在这里添加身份验证需要: // request.PreAuthenticate = true; // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; // request.Headers.Add(Authorization,Basic+ Convert.ToBase64String(System.Text.Encoding.D efault.GetBytes(用户名+:+密码))); //将表单数据发送到请求。 using(Stream requestStream = request.GetRequestStream()) { requestStream.Write(formData,0,formData.Length); requestStream.Close(); } 返回request.GetResponse()as HttpWebResponse; } $ / $ private static byte [] GetMultipartFormData(Dictionary< string,> postParameters,string boundary) { Stream formDataStream = new System.IO.MemoryStream(); bool needsCLRF = false; foreach(postParameters中的var param) { //感谢评论者的反馈,添加CRLF以允许要添加多个参数。 //在第一个参数上跳过它,将其添加到后续参数中。 if(needsCLRF) formDataStream .Write(encoding.GetBytes(\\\\ n),0,encoding.GetByteCount(\\\\ n)); needsCLRF = true; if(param.Value is FileParameter) { FileParameter fileToUpload =(FileParameter )param.Value; //只添加此参数的第一部分,因为我们将文件数据直接写入Stream string header = string.Format( - {0} \\\\ nConContent-Disposition:form-data; name = \{1} \ ; filename = \{2} \; \\\Content-Type:{3} \\\\\\\ n, border, param.Key, fileToUpload.FileName ?? param.Key, fileToUpload.ContentType ?? application / octet-stream); formDataStream.Write(encoding.GetBytes(header),0,encoding.GetByteCount(header)); //将文件数据直接写入Stream,而不是将其序列化为字符串。 formDataStream.Write(fileToUpload.File,0,fileToUpload .File.Length); } else { string postData = string.Format( - - {0} \\\\ nnContent-Disposition:form-data; name = \{1} \\\\\\ n {2}, 边界, param.Key, param.Value); formDataStream.Write(encoding.GetBytes(postData),0 ,encoding.GetByteCount(postData)); } } //添加结束请求。从换行符开始 string footer =\\\\ n - + boundary +--\\\\ n; formDataStream.Write (encoding.GetBytes(footer),0,encoding.GetByteCount(footer)); //将Stream转储成一个字节[] formDataStream.Position = 0; byte [] formData = new byte [formDataStream.Length]; formDataStream.Read(formData,0,formData.Length); formDataStream.Close(); 返回formData; } 公共类FileParameter { public byte [] File {get;组; } $ / $ 公共字符串FileName {get;组; } $ / $ 公共字符串ContentType {get;组; } $ / $ public FileParameter(byte [] file):this(file,null){} public FileParameter(byte [] file,string filename):this(file, filename,null){} public FileParameter(byte [] file,string filename,string contenttype) { File = file; FileName = filename; ContentType = contenttype; } } 现在从aspx.cs页面调用..就像这样.. !! protected void btnUploadAsset_Click(object sender,EventArgs e) { //读取文件数据 string strPath = Server.MapPath(〜/ shopping / asset.png); FileStream fs = new FileStream(strPath,FileMode.Open,FileAccess.Read); byte [] data = new byte [fs.Length]; fs.Read(data,0,data.Length); fs.Close(); //生成帖子对象 Dictionary< string,> postParameters = new Dictionary< string,>(); postParameters.Add(token,txtToken.Text); // @ postParameters.Add(fileformat ,png); postParameters.Add(file,new SheerIdcl.FileParameter(data,asset.png,image / png)); //创建请求并收到回复 string postURL =https://services-sandbox.sheerid.com/rest/0.5/asset\"; 串的userAgent = Mozila; HttpWebResponse WebResponse类= SheerIdcl.MultipartFormDataPost(postURL,的userAgent,postParameters); //处理响应 的StreamReader responseReader =新的StreamReader(webResponse.GetResponseStream()); 串fullResponse = responseReader.ReadToEnd(); webResponse.Close(); ltrUploadResponse.Text = fullResponse; } I am trying to upload image to restApi but it throws Internal server error.Please consider my code and guide me where i am missing somethingpublic void UploadAsset(string sToken, string sImage){string sRes = string.Empty;Uri address = new Uri("https://services-sandbox.sheerid.com/rest/0.5/asset");// Create the web requestHttpWebRequest oHttpWebRequest = WebRequest.Create(address) as HttpWebRequest;oHttpWebRequest.Credentials = new NetworkCredential("mrinalkumarjha", "******");oHttpWebRequest.Headers["Authorization"] = "Bearer 624a3eef46f79772958693fa87118b29";oHttpWebRequest.Method = "POST";oHttpWebRequest.ContentType = "multipart/form-data";// Create the data we want to sendstring sFile = "asset.png";StringBuilder data = new StringBuilder();data.Append("file=" + HttpUtility.UrlEncode(@sFile));data.Append("&failure=" + HttpUtility.UrlEncode("Your URL"));data.Append("&succes=" + HttpUtility.UrlEncode("Your URL"));data.Append("&token=" + HttpUtility.UrlEncode(txtToken.Text));// Create a byte array of the data we want to sendbyte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());// Set the content length in the request headersoHttpWebRequest.ContentLength = byteData.Length;// Write data.using (Stream postStream = oHttpWebRequest.GetRequestStream()){postStream.Write(byteData, 0, byteData.Length);}// Get responseusing (HttpWebResponse response = oHttpWebRequest.GetResponse() as HttpWebResponse){// Get the response streamStreamReader reader = new StreamReader(response.GetResponseStream());// Console application outputsRes = reader.ReadToEnd();}}[Edit]Code block added[/Edit] 解决方案 I have solved it .. add following in class file.private static readonly Encoding encoding = Encoding.UTF8;public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string,> postParameters){string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());string contentType = "multipart/form-data; boundary=" + formDataBoundary;byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);return PostForm(postUrl, userAgent, contentType, formData);}private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData){HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;if (request == null){throw new NullReferenceException("request is not a http request");}// Set up the request properties.request.Method = "POST";request.ContentType = contentType;request.UserAgent = userAgent;request.CookieContainer = new CookieContainer();request.ContentLength = formData.Length;request.Credentials = new NetworkCredential("mrinalkumarjha", "*****");request.Headers["Authorization"] = "Bearer 624a3eef46f79772958693fa87118b29";// You could add authentication here as well if needed:// request.PreAuthenticate = true;// request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;// request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));// Send the form data to the request.using (Stream requestStream = request.GetRequestStream()){requestStream.Write(formData, 0, formData.Length);requestStream.Close();}return request.GetResponse() as HttpWebResponse;}private static byte[] GetMultipartFormData(Dictionary<string,> postParameters, string boundary){Stream formDataStream = new System.IO.MemoryStream();bool needsCLRF = false;foreach (var param in postParameters){// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.// Skip it on the first parameter, add it to subsequent parameters.if (needsCLRF)formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));needsCLRF = true;if (param.Value is FileParameter){FileParameter fileToUpload = (FileParameter)param.Value;// Add just the first part of this param, since we will write the file data directly to the Streamstring header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",boundary,param.Key,fileToUpload.FileName ?? param.Key,fileToUpload.ContentType ?? "application/octet-stream");formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));// Write the file data directly to the Stream, rather than serializing it to a string.formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);}else{string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",boundary,param.Key,param.Value);formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));}}// Add the end of the request. Start with a newlinestring footer = "\r\n--" + boundary + "--\r\n";formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));// Dump the Stream into a byte[]formDataStream.Position = 0;byte[] formData = new byte[formDataStream.Length];formDataStream.Read(formData, 0, formData.Length);formDataStream.Close();return formData;}public class FileParameter{public byte[] File { get; set; }public string FileName { get; set; }public string ContentType { get; set; }public FileParameter(byte[] file) : this(file, null) { }public FileParameter(byte[] file, string filename) : this(file, filename, null) { }public FileParameter(byte[] file, string filename, string contenttype){File = file;FileName = filename;ContentType = contenttype;}}Now call it from aspx.cs page.. Like this..!!protected void btnUploadAsset_Click(object sender, EventArgs e){// Read file datastring strPath = Server.MapPath("~/shopping/asset.png");FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.Read);byte[] data = new byte[fs.Length];fs.Read(data, 0, data.Length);fs.Close();// Generate post objectsDictionary<string,> postParameters = new Dictionary<string,>();postParameters.Add("token", txtToken.Text);//postParameters.Add("fileformat", "png");postParameters.Add("file", new SheerIdcl.FileParameter(data, "asset.png", "image/png"));// Create request and receive responsestring postURL = "https://services-sandbox.sheerid.com/rest/0.5/asset";string userAgent = "Mozila";HttpWebResponse webResponse = SheerIdcl.MultipartFormDataPost(postURL, userAgent, postParameters);// Process responseStreamReader responseReader = new StreamReader(webResponse.GetResponseStream());string fullResponse = responseReader.ReadToEnd();webResponse.Close();ltrUploadResponse.Text = fullResponse;} 这篇关于将图像上传到REST API的问题.. !!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-30 09:12