Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说C# WebApi 文件上传与下载(最少代码解决方案)「终于解决」,希望能够帮助你!!!。
在使用C# 开发Api接口的时候,最难办的是文件上传和下载。网上教程很多,真正能使用的特别少,而且很多都是错误的。并且很多都特别复杂,也难以理解。
特地重整理。
[HttpGet]
public IHttpActionResult Get(string id)
{
return Json<dynamic>(new { code = "200", message = "true", data = new { fileUrl = "", id, time = DateTime.Now } });
}
private string uploadPath = "D:\\OrderAdminApiFile\\OrderUpload";
[HttpGet]
public HttpResponseMessage GetFile(string filename)
{
string path = "\\2020-09-04\\2020090416474099937.pdf";
string ext = Path.GetExtension(path);
var stream = new FileStream(#34;{uploadPath}\\{path}", FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = filename + ext
};
return response;
}
[HttpPost]
public IHttpActionResult PostFile(string filename)
{
string result;
string info = "";
var value = this.Request.Content.ReadAsStreamAsync();
if (value != null)
{
//获取文件后缀
string ext = Path.GetExtension(filename);
//设置路径
string filepath = #34;{ uploadPath} \\{ DateTime.Now:yyyy-MM-dd}\\";
//设置保存名称
string newFileName = #34;{ DateTime.Now:yyyyMMddHHmmssfffff}{ext}";
using (StreamWriter sw = new StreamWriter(#34;{filepath}\\{newFileName}"))
{
value.Result.CopyTo(sw.BaseStream);
sw.Flush();
}
result = "上传成功";
info = (filepath + newFileName);
Form1.StaticForm.logListBox1.AddFormat("上传文件: {0}", info);
}
else
{
result = "上传的文件信息不存在!";
}
return Json<dynamic>(new { code = "200", message = result, data = new { info } });
}
}
上一篇
已是最后文章
下一篇
已是最新文章