1 MVC中顯示 記憶體流 中的圖片。(不是圖片檔案)

建立一個Index用來顯示

Action:

public ActionResult Index()
{
return View();
}

cshtml:

@{
ViewBag.Title = "Index";
} <h2>Index2</h2>
<img src="[email protected]" height="136">

重點就是  <img src="[email protected]" 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();
} }

cshtml:

<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");
}