ajax +.net mvc 多图片上传加预览
@{
ViewBag.Title = "Index";
Layout = null;
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title> 上传多张图片</title>
</head>
<body>
<script src="~/scripts/jquery-3.3.1.js"></script>
<script type="text/javascript">
//选择图片,预览
function xmTanUploadImg(obj) {
var imgTypes = new Array();
imgTypes[0] = "JPG";
imgTypes[1] = "ICO";
imgTypes[2] = "PNG";
imgTypes[3] = "GIF";
imgTypes[4] = "JPEG";
imgTypes[5] = "TGA";
var num=0;//选错图片格式的个数
var fl = obj.files.length;
if(fl<=7){
for(var i = 0; i < fl; i++) {
var file = obj.files[i];
//判断图片格式
var filename = obj.files[i].name;
imgType = filename.substring(filename.lastIndexOf(".") + 1, file.length)
var reader = new FileReader();
//判断是否是图片格式
if (imgType.toUpperCase()==imgTypes[0]||imgType.toUpperCase()==imgTypes[1]||imgType.toUpperCase()==imgTypes[2]||imgType.toUpperCase()==imgTypes[3]||imgType.toUpperCase()==imgTypes[4]||imgType.toUpperCase()==imgTypes[5]) {
reader.onload = function(e) {
img = document.createElement("img");
img.src = this.result;
img.style.width = "80px";
img.style.height = "100px";
document.getElementById("showimg").appendChild(img);
$("#upload").attr("disabled",false);
}
} else{
num++;
alert("你选择的图片格式不正确:"+num+"张图片格式不正确");
$("#upload").attr("disabled",true);
}
reader.readAsDataURL(file);
}
}else{
alert("每次只能上传7张图片");
}
}
function Upload() {
var param = new FormData(($("#form")[0]));
$.ajax({
url: "/Upload.ashx",
data: param,
type:"post",
processData: false,
contentType: false,
success: function (data) {
alert(data)
}
})
}
</script>
<form method="post" enctype="multipart/form-data" id="form" >
<input type="file" name="file" id="file" multiple="multiple" onchange="xmTanUploadImg(this)" />
<input type="button" value="上传" onclick="Upload()" />
</form>
<!--图片显示位置-->
<div id="showimg">
</div>
</body>
一般处理程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication5
{
/// <summary>
/// Upload 的摘要说明
/// </summary>
public class Upload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
var num = context.Request.Files.Count;
for (int i = 0; i < num; i++)
{
HttpPostedFile file = context.Request.Files[i];
//上传的文件保存到目录(为了保证文件名不重复,加个Guid)
string path = "/Upload/" + Guid.NewGuid().ToString() + file.FileName;
file.SaveAs(context.Request.MapPath(path));//必须得是相对路径
}
context.Response.Write("上传成功");
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
这个后台没有对是否是图片进行验证 所以 实际用到 要加上类型判断