在chhtml页中添加标签
<form method="post" enctype="multipart/form-data" id="formData">
<input type="hidden" name="FileName" value="" />
<span>上传图片</span>
<input type="file" id="fileUpload" name="file" /><span>上传图片input 后给id必须给个name="file"</span>
<img src="" id="showImage" />
</form>
<script type="text/javascript">
$(function () {
$("#fileUpload").change(function () {
//单文件长传所以默认取第一个
var formData = new FormData($("#formData")[0]);
$.ajax({
url: '/Product/UploadFile',
type: 'post',
//数据类型不处理
contentType: false,
//数据不处理
processData: false,
//不缓存
cache: false,
data:formData,
success: function (data) {
alert(data)
$("input[name=FileName]").val(data);
$("#showImage").attr("src", data);
}
});
});
})
</script>
后台代码
public string UploadFile()
{
HttpPostedFileBase httpfile = Request.Files[0];
if (httpfile != null)
{
//获取路径
string strPath = Server.MapPath("~/images/");
//判断是否存在
if (!Directory.Exists(strPath))
Directory.CreateDirectory(strPath);
//获取所有路径
string newPath = Path.Combine(strPath, httpfile.FileName);
httpfile.SaveAs(newPath);
return "/images/" + httpfile.FileName;
}
else
return null;
}