1 MVC中显示 内存流 中的图片。(不是图片文件)
创建一个Index用来显示
Action:
public ActionResult Index()
{
return View();
}
@{
ViewBag.Title = "Index";
}
Index2
重点就是
public ActionResult GetImg(string qrCode)
{
var q = new MemoryStream();//这里是你的图片 内存流
return File(q.ToArray(), "image/jpeg");
}
2 WebApi 中上传文件
Action: 我的webapi访问路径是 api/common/UploadFile
///
/// 上传图片
///
///
public async Task UploadFile()
{
// 检查是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
HttpResponseMessage response = null;
try
{ //UploadImgUrl 为绝对路径
var provider = new RenamingMultipartFormDataStreamProvider(UploadImgUrl);
var body = await Request.Content.ReadAsMultipartAsync(provider);
//获取改写后的文件名(会再次调用GetLocalFileName)
//result.data = provider.GetLocalFileName(provider.FileData[0].Headers);
//获取改写后的文件名(不会再次调用GetLocalFileName)
//result.data = body.FileData[0].LocalFileName.Substring(body.FileData[0].LocalFileName.LastIndexOf('\\'));
response = Request.CreateResponse(HttpStatusCode.OK);
}
catch
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
return response;
}
创建一个 Provider 用于重命名接收到的文件
public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public RenamingMultipartFormDataStreamProvider(string path)
: base(path)
{ }
public override string GetLocalFileName(HttpContentHeaders headers)
{
var sb = new StringBuilder((headers.ContentDisposition.FileName ?? DateTime.Now.Ticks.ToString()).Replace("\"", "").Trim().Replace(" ", "_"));
Array.ForEach(Path.GetInvalidFileNameChars(), invalidChar => sb.Replace(invalidChar, '-'));
return sb.ToString();
}
}
3 MVC上传图片:
前台:
@using (Html.BeginForm("Test", "Test", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
后台:
[ValidateInput(false)]
[HttpPost]
public ActionResult Test(HttpPostedFileBase up1)
{
if (up1!=null&&up1.FileName != "")
{
up1.SaveAs(imgFilePath);//文件保存,imgFilePath:文件路径+文件名
}
return View();
}
4 Ajax上传图片:
前台:
后台:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
return RedirectToAction("Index");
}