c#后台通过API Post传图片到SM.MS服务器

Logerlink 2020-02-12 06:17:37
大佬新年好,有一问请教,望不吝发言
文档:https://doc.sm.ms/#api-Image-Upload
token可以用这个:kIx4W27pUnzR5pW4oiChWf06dYrlhbZQ


public static void UploadImage(string imgPath, string token)
{
const string BASE_SMMS_URL = "https://sm.ms/api/v2";
imgPath = HttpUtility.UrlDecode(imgPath, Encoding.UTF8);
if (imgPath.StartsWith("file:///")) imgPath = imgPath.Split(new string[] { "file:///" }, StringSplitOptions.None)[1];
if (!File.Exists(imgPath))
{
throw new Exception("不存在该图片");
}
var postUrl = BASE_SMMS_URL + "/upload";
HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.Headers["Authorization"] = token;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 Edg/80.0.361.48";

string boundary = DateTime.Now.Ticks.ToString("x");
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

int pos = imgPath.LastIndexOf("\\");
string fileName = imgPath.Substring(pos + 1);

//请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, 0, bArr.Length);
fs.Close();

Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bArr, 0, bArr.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
postStream.Close();

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
string content = sr.ReadToEnd();
}

python实现参考:https://blog.csdn.net/mbh12333/article/details/102860282

...全文
592 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
养 家 糊 口 2021-05-20
  • 打赏
  • 举报
回复
大佬是怎么解决的?
Logerlink 2020-02-13
  • 打赏
  • 举报
回复
强!
早上同事做出来了。。。
github_36000833 2020-02-13
  • 打赏
  • 举报
回复
请求里面的form-data的名字不是file,应按说明书写成smfile 请求: POST /api/v2/upload HTTP/1.1 Authorization: kIx4W27pUnzR5pW4oiChWf06dYrlhbZQ Host: sm.ms Content-Type: multipart/form-data; boundary=--------------------------433199921807626829858605 Content-Length: 4549 Connection: keep-alive ----------------------------433199921807626829858605 Content-Disposition: form-data; name="smfile"; filename="task-view.png" <task-view.png的二进制数据...> ----------------------------433199921807626829858605-- 答复: HTTP/1.1 200 OK Server: nginx Date: Thu, 13 Feb 2020 06:23:52 GMT Content-Type: text/html; charset=UTF-8 Transfer-Encoding: chunked Connection: keep-alive Vary: Accept-Encoding Set-Cookie: PHPSESSID=52ms2mggoqq8cbdeq2sj1hicug; path=/ Set-Cookie: cid=rBWawl5E63hr1Ti7GosxAg==; expires=Thu, 31-Dec-37 23:55:55 GMT; domain=sm.ms; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate Pragma: no-cache Strict-Transport-Security: max-age=63072000; includeSubDomains; preload X-Frame-Options: SAMEORIGIN X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block X-Custom-Job: If you see this, please contact hello@cat.net for a job Access-Control-Allow-Origin: * Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST Allow: GET, POST, HEAD Content-Encoding: gzip {"success":true,"code":"success","message":"Upload success.","data":{"file_id":0,"width":150,"height":39,"filename":"task-view.png","storename":"raWIo93xh71kfbQ.png","size":4337,"path":"\/2020\/02\/13\/raWIo93xh71kfbQ.png","hash":"uoXZ754lgjzdM2G8ihKpHyLPYx","url":"https:\/\/i.loli.net\/2020\/02\/13\/raWIo93xh71kfbQ.png","delete":"https:\/\/sm.ms\/delete\/uoXZ754lgjzdM2G8ihKpHyLPYx","page":"https:\/\/sm.ms\/image\/raWIo93xh71kfbQ"},"RequestId":"28969B54-9325-4895-A5AF-9940CB165925"}

111,094

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧