最近在做一个项目, 需要静态上传文件到后台,并且在没有提交表单前可以查看上传的文件,看公司代码,都是使用 ifrome 标签实现的, 比较麻烦,于是发现有更简单的方法,支持ajax静态上传,支持上传多文件,好了,废话少说,直接上代码吧
demo下载:demo-UploadFile
前台页面代码:
<h1>注意:ie浏览器必须是ie10及以上版本才可以</h1>
<input type="file" id="fileUpload" />
<img src="" style="display:none" id="img-show" />
<input type="button" value="ajax静态上传图片" id="ajax-btn" />
Jquery代码:
<script type="text/javascript">
$(function () {
fileUpload();
Ajaxbtn();
});
function fileUpload() {
$("#fileUpload").change(function () {
var Suffix = $(this).val().substring($(this).val().lastIndexOf('.'));
if (Suffix == ".jpg" || Suffix == ".jpeg" || Suffix == ".png" || Suffix == ".bmp") {
//加载图片
var file = document.getElementById("fileUpload").files[0];
var img = document.getElementById("img-show"); //获取img对象
var reader = new FileReader(); //建一条文件流来读取图片
reader.readAsDataURL(file); //根据url将文件添加的流中
//实现onload
reader.onload = function (e) {
url = reader.result; //获取文件在流中url
img.src = url; //将url赋值给img的src属性
};
$("#img-show").css("display", "block");
}
else {
alert("图片格式不正确!(正确格式:.jpg、.jpeg、.png、.bmp)");
}
});
}
function Ajaxbtn() {
$("#ajax-btn").click(function () {
//判断是否有要上传的文件
var length = $("#fileUpload").prop("files").length;
if (length > 0) {
var formData1 = new FormData();
// 遍历要上传的文件
for (var i = 0; i < length; i++) {
formData1.append('fileName' + (i + 1), $("#fileUpload").prop("files")[i]);
}
// 提交图片数量
formData1.append('count', length);
//开始上传图片
if (length > 0) {
$.ajax({
url: 'Handler.ashx',
type: 'POST',
data: formData1,
contentType: false,
processData: false,
async: false,
success: function (json) {
if (json.status == "true") {
alert("上传成功!文件名为:" + json.data);
}
else {
alert(json.msg);
return false;
}
},
error: function () {
}
})
}
}
else {
alert("请上传图片");
}
});
}
</script>
后台操作
using System;
using System.Web;
using System.Web.Script.Serialization;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
if (context.Request.Files.Count > 0)
{
int count = Convert.ToInt32(context.Request["count"]);
string pathArray = string.Empty;
Random ran = new Random();
//判断上传图片的数量
for (int i = 1; i <= count; i++)
{
//获取文件
var fileName = "fileName" + (i).ToString();
HttpPostedFile file = context.Request.Files[fileName];
//获取后缀名
string imgtype = System.IO.Path.GetExtension(file.FileName);
//判断是不是图片
if (imgtype != ".jpg" && imgtype != ".jpeg" && imgtype != ".png" && imgtype != ".bmp" && imgtype != ".jpeg")
{
WriteJson(context.Response, "error", "图片格式不正确");
break;
}
else
{
//拼接文件名
string name = DateTime.Now.ToString("yyyyMMddHHmmss") + ran.Next(100, 500) + imgtype;
//文件路径
string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + string.Format(@"img\{0}",name);
//保存
file.SaveAs(path);
//拼接保存到数据汇总的数据
pathArray += name+";";
}
}
if (pathArray.Length > 0)
{
WriteJson(context.Response, "true", null, pathArray);
}
}
else
{
WriteJson(context.Response, "error", "请选择要上传的文件");
}
}
public static void WriteJson(HttpResponse response, string status1, string msg1, object data1 = null)
{
response.ContentType = "application/json";
var obj = new { status = status1, msg = msg1, data = data1 };
string json = new JavaScriptSerializer().Serialize(obj);
response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
}