Ajax對Form表單圖片的區域性上傳
首先引入jquery.form.js
1.建立一個form表單(("~/Content/productPic/")是儲存圖片的路徑)
@using(Html.BeginForm("UploadIcon","FlowChartForm",FormMethod.Post,new {ID="uploadpic",enctype="multipart/form-data"}))
{
<input type="file" name="imgfile" onchange="$('#uploadpic').submit();" style="width:200px;"/><br/>
<img id="imgicon" src="@(Url.Content("~/Content/productPic/")+
ViewData["picName"])" style="display:none;width:80px;height:60px;"/>@Html.Hidden("iconurl",ViewData["picName"]);
}
2.使用ajax提交圖片(進行ajaxt提交的方法)
$(function(){
$('uploadpic').ajaxForm({
success:function(data){
var data=jQuery.parseJSON(data);
if(data!=undefined&&data!=null){
if(data.msg==0){
alert("請上傳圖片!");
return;
}else if(data.msg==-1){
alert("檔案格式不正確!");
return;
}else if(data.mag==-2){
alert("上傳圖片不能超過3M!");
return;
}else if(data.msg==-3){
alert("出現異常,請稍後再試")!\
return;
}else{
//如果你上傳到的是本地可以這樣寫
//var path="@Url.Content("../Content/productPic")"+data.msg;
//$("#imgicon").attr("src",path);
//$("#imgicon").show();
downpic(data.msg);
}
}
}
})
});
function downpic(msg){
$("#imgicon").attr("src",url)顯示圖片
$("iconurl).val(msg)
$("#imgicon").show();
}
3.後臺程式碼
[HttpPost]
public JsonResult UploadIcon(HttpPostedFileBase imgfile)
{
try
{
if(imgfile==null)
{
return Json(new{msg=0},"text/html");
}else
{
var supportTypes=new []{"jpg","jpeg","png","gif","bmp"};
var fileExt=System.IO.Path.GetExtension(imgfile.FileName).Substring(1);
if(!supportTypes.Contains(fileExt))
{
return Json(new {msg=-1},"text/html");
}
if(imgfile.ContentLength>1024*1000*3)
{
return Json(new {msg=-1},"text/html");
}
Random r=new Random();
var filename=DateTime.Now.ToString("yyyyMMddHHmmss")+r.Next(10000)+"."+fileExt;
//var filepath=System.IO.Path.Combine(Server.MapPath("~/Content/productPic/"),filename);
//imgfile.SaveAs(filepath);
string savepath="d:\\pic\\;
bool IsUpdate=ServerFileHelper.UploadFile(imgfile.InputStream,savepath,filename)//上傳到伺服器的方法,看下一個文章
if(IsUpdate){
savepath=savepath+filename;
}
ViewData["picName"]=filepath;
return Json(new {msg=savepath},"text/html");
}
}catch(Execption e)
{
return Json(new{msg=-3},"text/html");
}
}
public void DownLoadPic()
{
string filePath=Request.QueryString["filePath"];
filePath=filePath.Replace("\\\\","\\");
Stream FileStream=ServerFileHelper.DownLoadFile(filePath,"pp.jpg");
Response.ClearContent();
Response.ContentType="image/png";
Image img=Image.FormStream(FileStream);
img.Save(Response.OutputStream,ImageFormat.Png);
img.Dispose();
Response.OutputStream.Flush();
Response..OutputStream.Close();
}
}
注意:我引入form.js之後使用ajaxForm方法,提示物件對定義,然後我就感覺奇了怪,這根本就是不科學的,後來找啊找,最後把開頭的引入模板設定為null就行啦,哎。。。。
@{
Layout=null;
}