Uploadify是来自国外的一款优秀jQuery插件,主要功能是批量上传文件,此插件在项目中已被广泛之用,但是也发现不少问题。话不多说,看源码。
jq:
<script>
jQuery(function () {
$('#PickImage').uploadify({
'swf': '/Content/uploadify.swf', 'buttonText': '选择图片并上传',
'uploader': '/ActiveManage/UploadImage?imgpath=' + $("#picpath").val(),
'fileTypeDesc': '图片类型',
'fileTypeExts': '*.jpg;*.jpeg;*.png',
"formData": { "folder": "/product/" },
onUploadSuccess: function (localFileObject, serverData, receivedResponse) {
//console.log(serverData)
if (typeof (serverData) == "string")
serverData = JSON.parse(serverData);
$("#HeadImgurl").val(serverData.ImagePath);
$("#Rimg").attr("src", serverData.ImagePath);
$("#picpath").val(serverData.ImagePath);
//this.uploader.ImagePath = '/ActiveManage/UploadImage?imgpath=' + $("#picpath").val();
$('#PickImage').uploadify('settings', 'uploader', '/ActiveManage/UploadImage?imgpath=' + $("#picpath").val())
},
onUploadComplete: function (fileObj) {
}
});
});
</script>
html :
<div class="form-group" style="margin-left:10px;">
<img class="img-rounded" id="Rimg" width="130" height="130" src="/UploadPic/selectpic.png" />
</div>
<div class="form-group" style=" margin-left:10px;">
<input class="form-control" type="file" id="PickImage" name="PickImage" value="浏览图片" />
<input type="text" id="picpath" name="picpath" style="display:none;" />
</div>
controller:
public ActionResult UploadImage(string imgpath)
{
if (System.IO.File.Exists(imgpath))
{
System.IO.File.Delete(imgpath);
}
Response.ContentType = "text/plain";
Response.Charset = "utf-8";
HttpPostedFileBase file = Request.Files["Filedata"];
string path = ConfigurationManager.AppSettings["Domain"].ToString(); //填写服务器域名
string timenow = DateTime.Now.ToString("yyyyMMdd");
string basePath = "/UploadPic/" + timenow + "/";
string uploadPath = Server.MapPath(basePath); //本地路径
if (file != null)
{
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string fileName = file.FileName;
string ext = fileName.Substring(fileName.LastIndexOf("."));
fileName = DateTime.Now.Ticks + ext;
file.SaveAs(uploadPath + fileName);
//服务器上传
//return Json(new { ImagePath = string.Format("{0}{1}{2}", path, basePath, fileName) });
//本地上传
return Json(new { ImagePath = string.Format("{0}{1}", basePath, fileName) });
}
else
{
return Json(new { error = 0 });
}
}