MVC ajax 上传文件

时间:2023-03-09 06:53:00
MVC ajax 上传文件

废话不多说,上代码:

用到的js文件:

jquery.min.js

jquery.easyui.min.js

<input id="fileurl" onclick="$('#imageUpLoad').click();"/>
<input type="button" value="上传" onclick="document.getElementById('form1').submit();"> <div style="display:none; position:absolute; top:0; left:0;">
<iframe name="uploadResponse"></iframe>
<form id="form1" runat="server" action="/UploadFile/UpLoadImage/" method="post" enctype="multipart/form-data" target="uploadResponse">
<input type="file" id="imageUpLoad" name="imageUpLoad" style="display:none;" onchange="$('#fileurl').attr('isLoad','0');">
<input id="imageType" name="imageType" value="floor" style="display:none;"/>
</form>
<script type="text/javascript">
function CallBack(path) {
$("#fileurl").attr('isLoad', '1').val(path);
$.messager.alert('提示信息', '上传成功!', 'info');
}
</script>
</div>

isLoad 属性是我自己添加的属性,用来判断图片是否提交

ps:记得在window.load事件中初始化这个属性,因为低版本的ie不支持<input isLoad="1"/>这种格式

后台代码

using System.Web;
using System.Web.Mvc;public class UploadFileController : Controller
{
//
// GET: /UploadFile/ public ActionResult Index()
{
return View();
} public void UpLoadImage(HttpPostedFileBase imageUpLoad, string imageType)
{
string returnFilePath = imageUpLoad.FileName;
//这里是我自己写的一段创建文件路径并保存的代码,可以直接imageUpLoad.SaveAs("文件路径");来保存
Helper.SaveFile(imageUpLoad, Helper.FileType.Images, imageType, ref returnFilePath); returnFilePath = returnFilePath.Replace("\\", "/"); Response.Write(string.Format("<script type='text/javascript'>window.parent.CallBack('" + returnFilePath + "');</script>"));
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO; public class Helper
{  

    /// <summary>
    /// 文件类型
    /// </summary>
    public enum FileType {
      Images,
      Files
    }

    public static bool SaveFile(HttpPostedFileBase f, FileType ft, string separator,ref string path)
{
try
{
string FilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ft.ToString());
if (!Directory.Exists(FilePath))
Directory.CreateDirectory(FilePath); FilePath = Path.Combine(FilePath, separator);
if (!Directory.Exists(FilePath))
Directory.CreateDirectory(FilePath); FilePath = Path.Combine(FilePath, path);
f.SaveAs(FilePath);
path = Path.Combine(ft.ToString(), separator, path);
return true;
}
catch (Exception ex){
LogHelper.Error(ex);
}
return false;
}
}

这里主要说明一下html界面form的参数:

action : 你的mvc处理文件上传的路径

method:提交方式

enctype:这个一定要写对“multipart/form-data”

target:值“uploadResponse”表示回传的接收页面地址,这里是一个iframe,避免了回传刷新页面

后台cs代码说明:

UpLoadImage:方法名要和地址一致
参数:
HttpPostedFileBase imageUpLoad  
imageUpLoad 应该是上传文件控件的name值
string imageType

同上iamgeType 为文本控件的name值
如果你有多个参数需要传递到后台,可以按照这个格式自定义参数个数 当然还有一种方法可以放函数不带参数
使用request来处理传递过来的文件和参数,请网上自行查阅资料。