最近做了一个爬虫,把网站的数据爬下来,但是数据需要分发到自己的各个网站,数据中的图片有外链有本站保存的图片,需要将图片文件上传到服务器。
上代码
WebAPI (.net core 3.1)
[HttpPost]
public ActionResult PostImage(string imgname)
{
//图片保存路径
var date = DateTime.Now.ToString("yyyyMMdd");
var path = Path.Combine(imgsavepath, "UploadFile", date);
string fullName = string.Empty;
//Request.Form.Files获取客户端POST过来的所有文件
IFormFileCollection files = Request.Form.Files;
foreach (FormFile file in files) //遍历处理每一个文件
{
//Path.GetExtension()获取文件扩展名
string exten = Path.GetExtension(file.FileName).ToLower();
//扩展名不符合要求就不处理
if (exten != ".jpg" && exten != ".png") continue;
//Guid.NewGuid().ToString()生成一个GUID风格的文件名避免重名
//string fileName = Guid.NewGuid().ToString();
string fileName = file.FileName;
fullName = Path.Combine(path, fileName);
//用using语句释放文件资源
using (FileStream stream = new FileStream(fullName, FileMode.Create, FileAccess.Write))
{
file.CopyTo(stream);
stream.Flush();
}
}
return Content("{'result':'ok'}");
}
Winform (.net framework 4.8.1)
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:27154/bbs/PostImage"); //实例化WebRequest对象
request.KeepAlive = true;
request.Date = DateTime.Now;
request.Accept = "*/*";
//request.ContentType = "text/html";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
request.Method = "Post";
request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
request.ProtocolVersion = HttpVersion.Version10;
request.Timeout = 30000;
//using (Stream reqStream = request.GetRequestStream())
//{
// //reqStream.Write(data, 0, data.Length);
// //reqStream.Close();
//}
var filePath = "D:\\Code\\PostBBS\\bin\\Debug\\NAVER.png";
//读取file文件
//FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
//BinaryReader binaryReader = new BinaryReader(fileStream);
try
{
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
int pos = filePath.LastIndexOf("\\");
string fileName = filePath.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(filePath, 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();
}
catch (Exception ex)
{
MessageBox.Show("文件传输异常: " + ex.Message);
}
finally
{
//fileStream.Close();
//binaryReader.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var responsestream = response.GetResponseStream();
Encoding ec = Encoding.UTF8;
StreamReader reader = new StreamReader(responsestream, ec);
var htmlStr = reader.ReadToEnd();
MessageBox.Show(htmlStr);
}