C# RestSharp上传和下载图片
上传图片到服务器
C# RestSharp上传图片服务器代码
C# 全选
/// <summary>
/// SEO图片上传
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost]
public HDFile SEOImage(IFormFile file)
{
var dir = PathProvider.GetRootSEOPath();
var data = SaveImage(file, dir, false, false);
string tag = "seo";
AddDB(data, tag);
return new HDFile(data.fileName, $"/images/{tag}/{data.fileName}", "");
}
ImageInfoModel SaveImage(IFormFile file, string dir, bool enableImageMask, bool compression = true)
{
//如果路径不存在,创建路径
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
ImageInfoModel data = new ImageInfoModel();
data.relativePath = RelativePath(dir);
var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
data.fileID = strDateTime + strRan;
using (var memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
using (var img = Image.FromStream(memoryStream))
{
//文件后缀
data.extension = "." + img.RawFormat.ToString().ToLower();
string filename = dir + "\\" + data.fileName;
if (img.RawFormat.Equals(ImageFormat.Jpeg)
|| img.RawFormat.Equals(ImageFormat.Bmp)
|| img.RawFormat.Equals(ImageFormat.Png)
)
{
// 压缩图片?
if (compression)
{
ImageLibrary.SaveByCompression(img, filename, 90);
}
}
img.Save(filename);
}
}
return data;
}
C# RestSharp上传图片客户端代码
C# 全选
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jgp;*.png;*.jpeg;*.bmp;*.gif";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string url = txt_host.Text + "/api/upload/" + cmb_Type.SelectedValue;
RestClient client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
foreach (var v in cookies)
{
request.AddParameter(v.Name, v.Value, ParameterType.Cookie);
}
string imgFileName = openFileDialog.FileName;
//string imgName = System.IO.Path.GetFileName(imgFileName);
request.AddFile("file", imgFileName);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
下载图片
方法一,文件名可以从响应信息中分析
C# 全选
RestClient client = new RestClient(txt_ImageURL.Text);
client.ClearHandlers();
client.AddHandler("*", () => { return new JsonDeserializer(); });
RestRequest request = new RestRequest(Method.GET);
IRestResponse response = await client.ExecuteAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
// Read bytes
byte[] fileBytes = response.RawBytes;
var headervalue = response.Headers.FirstOrDefault(x => x.Name == "Content-Disposition")?.Value;
string fileName = "";
if (headervalue != null)
{
// 有返回文件名
string contentDispositionString = Convert.ToString(headervalue);
ContentDisposition contentDisposition = new ContentDisposition(contentDispositionString);
fileName = contentDisposition.FileName;
}
else
{
// 没有文件名,根据URL获得文件名
string _str = response.ResponseUri.Segments[response.ResponseUri.Segments.Length - 1];
if (System.IO.Path.GetExtension(_str) != "")
fileName = _str;
}
// 保存文件到磁盘
string fileFullName = "D:\\" + fileName;
using (var writer = File.OpenWrite(fileFullName))
{
writer.Write(fileBytes, 0, fileBytes.Length);
}
}
方法二:需要预先指定文件名
C# 全选
RestClient client = new RestClient(txt_ImageURL.Text);
var req = new RestRequest(Method.GET);
req.ResponseWriter = responseStream =>
{
using (responseStream)
{
// 保存文件到磁盘
string fileFullName = "D:\\test.png";
using (var writer = File.OpenWrite(fileFullName))
{
responseStream.CopyTo(writer);
}
}
};
var response = client.DownloadData(req);
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员