ajaxFileUpload

 

html:

<div class="imgbox" style="display: none">
<img id="upImg" alt="上传成功啦" src="" style="width: 690px; height: 220px;" runat="server"/>
</div>
<input type="file" id="fileImage" name="file" />
<div class="tiplb" style="margin-top: 10px; line-height: 25px">
格式:jpg、png,大小 1M 以内 ,
尺寸:<span style="color: red; font-weight: 600">690px*220px</span>
</div>

 

js:

$("#fileImage").change(function () {
ajaxFileUpload();
})

function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: '/ajaxapp/NewLive.ashx/upload?action=uploadImg', //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'fileImage', //文件上传域的ID
dataType: 'text', //返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
if (data != "") {
var obj = eval("(" + data + ")");
if (obj.code == "200") {
$("#upImg").attr("src", obj.data);
$(".imgbox").show();
layer.msg(obj.msg);
} else {
layer.msg(obj.msg);
}
} else {
layer.msg("异常!");
}
},
error: function (data, status, e)//服务器响应失败处理函数
{
layer.msg(e);
}, complete: function () {
$('#fileImage').replaceWith('<input type="file" id="fileImage" name="file" />');
$("#fileImage").change(function () {
ajaxFileUpload();
})
}
}
)
return false;
}

 


后台代码

HttpFileCollection files = context.Request.Files;
string msg = string.Empty;
string error = string.Empty;
string imgurl;
string path = "/resources/upload/NewLive/";//上传保存的路径
if (files.Count > 0)
{
string ImgExtention = System.IO.Path.GetExtension(files[0].FileName);
int ImgSize = files[0].ContentLength;
if (!(ImgExtention == ".jpg" || ImgExtention == ".JPG" || ImgExtention == ".png" || ImgExtention == ".PNG"))
{
rd.code = 0;
rd.msg = "上传失败!图片格式异常!";
rd.status = "error";
return JsonConvert.SerializeObject(rd);

}
if ((ImgSize / 1024) > 1024)
{
rd.code = 0;
rd.msg = "上传失败!图片不大于1M!";
rd.status = "error";
return JsonConvert.SerializeObject(rd);
}

if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
}
files[0].SaveAs(HttpContext.Current.Server.MapPath(path) + System.IO.Path.GetFileName(files[0].FileName));
msg = " 上传成功!";
imgurl = path + files[0].FileName;

 

 

posted @ 2020-07-16 09:20  zeroooooo~  阅读(136)  评论(0)    收藏  举报