MVC WebApi 图片上传和显示
1 MVC中显示 内存流 中的图片。(不是图片文件)
创建一个Index用来显示
Action:
public ActionResult Index()
{
return View();
}
@{
ViewBag.Title = "Index";
}
<h2>Index2</h2>
<img src="GetImg?qrCode=@Model.ListNo" height="136">
重点就是 <img src="GetImg?qrCode=@Model.ListNo" height="136"> 其实他指向了一个action,专门显示图片。
public ActionResult GetImg(string qrCode)
{
var q = new MemoryStream();//这里是你的图片 内存流
return File(q.ToArray(), "image/jpeg");
}
2 WebApi 中上传文件
Action: 我的webapi访问路径是 api/common/UploadFile
/// <summary>
/// 上传图片
/// </summary>
/// <returns></returns>
public async Task<HttpResponseMessage> 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();
}
}
<form name="form1" method="post" enctype="multipart/form-data" action="/api/common/UploadFile">
<div>
<label for="image1">Image File</label>
<input name="image1" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
3 MVC上传图片:
前台:
@using (Html.BeginForm("Test", "Test", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="up1" type="file" />
<input type="submit" value="Submit"/>
}
后台:
[ValidateInput(false)]
[HttpPost]
public ActionResult Test(HttpPostedFileBase up1)
{
if (up1!=null&&up1.FileName != "")
{
up1.SaveAs(imgFilePath);//文件保存,imgFilePath:文件路径+文件名
}
return View();
}
4 Ajax上传图片:
前台:
<form id="form1">
<input type="file" id="file" name="file"/>
<input type="button" value="提交" onclick="sub()" />
</form>
<script>
function sub() {
var formData = new FormData();
formData.append("file", document.getElementById("file").files[0]);
$.ajax({
url: "/Test/UploadFile",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (data) {
}
});
}
</script>
后台:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
return RedirectToAction("Index");
}