1、下载jQuery.Form 包
官网下载:http://jquery.malsup.com/form/#download
2、模拟代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>上传图片测试</title>
<script src="js/jquery-1.8.2.js"></script>
<script src="js/jquery.form.js"></script> <script type="text/javascript">
function UpdateUserInfo() {
var Id = $("input[name='Id']").val();
var NickName = $("input[name='NickName']").val();
var RealName = $("input[name='RealName']").val();
$("#formDemo").ajaxSubmit({
url: '/Test/Submit?Id='+Id+'&RealName='+RealName+'&NickName='+NickName, /*设置post提交到的页面*/
type: "post", /*设置表单以post方法提交*/
headers:
{
AuthCode: "123456789"
},
dataType: "json", /*设置返回值类型为文本*/
success: function (data) {
//alert(data);
var txt = "<p>Id:"+data.Id+"</p><p>RealName:"+data.RealName+"</p><p>NickName:"+data.NickName+"</p><p><img src='"+data.HeadUrl+"' /></p>";
$("#txt").empty().append($(txt));
},
error: function (error) {
alert(error);
console.info(error);
} });
} function submitForm() {
UpdateUserInfo();
}
</script> </head>
<body>
<h1>上传图片测试</h1>
<form id="formDemo" method="post" enctype="multipart/form-data">
<input type="hidden" name="Id" value="69A26DD9-4A83-47DC-B0A1-172224037C95" /> <br /><br />
RealName: <input type="text" name="RealName" value="RealName" /><br /><br />
NickName: <input type="text" name="NickName" value="NickName" /><br /><br />
头像:<input type="file" name="HeadUrl" /> <br /><br />
<input type="button" value="测试" onclick="submitForm()" /> </form>
<div id="txt"> </div>
</body>
</html>
3、action 代码:
/// <summary>
/// 上传文件 修改上传文件名称 也不包含后缀名
/// </summary>
/// <returns></returns>
[HttpPost, Route("Submit")]
public async Task<JsonResult<UserModel>> Submit(string Id,string RealName,string NickName)
{
try
{
string headUrl = string.Empty;
//web api 获取项目根目录下指定的文件下
var root = System.Web.Hosting.HostingEnvironment.MapPath("/Resource/Images");
//对上传文件重新命名 根据需求对应修改文件名称 不包含后缀名 只是前缀名
var provider = new RenamingMultipartFormDataStreamProvider(root); //文件已经上传 但是文件没有后缀名 需要给文件添加后缀名
await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.FileData)
{
//这里获取含有双引号'" '
string filename = file.Headers.ContentDisposition.FileName.Trim('"');
//获取对应文件后缀名
string fileExt = filename.Substring(filename.LastIndexOf('.')); FileInfo fileinfo = new FileInfo(file.LocalFileName);
//fileinfo.Name 上传后的文件路径 此处不含后缀名
//修改文件名 添加后缀名
string newFilename = fileinfo.Name + fileExt;
//最后保存文件路径
string saveUrl = Path.Combine(root, newFilename);
fileinfo.MoveTo(saveUrl); headUrl = "/Resource/Images/" + newFilename;
}
UserModel model = new UserModel()
{
Id = Id,
NickName = NickName,
RealName = RealName,
HeadUrl = headUrl
}; return Json<UserModel>(model);
}
catch (Exception ex)
{
throw ex;
}
}