多图上传在一些特殊的需求中我们经常会遇到,其实多图上传的原理大家都有各自的见解。对于Layui多图上传和我之前所说的通过js获取文本框中的文件数组遍历提交的原理一样,只不过是Layui中的upload.render方法已经帮我们封装好了,我们只管调用即可,也就是说你选中了几张图片,那么将会向后台请求与图片张数相同的次数,即为遍历提交的方式。
前端:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test04.aspx.cs" Inherits="MyProject.Test04" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>多图上传</title>
<meta name="renderer" content="webkit" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<link href="/JS/layui/css/layui.css?v=1.0" rel="stylesheet" />
<link href="/layuiadmin/style/admin.css?v=1.0" rel="stylesheet" />
<%--以下两条是弹confirm需要--%>
<link href="/css/bootstrap.min.css?v=1.0" rel="stylesheet" />
<link href="/CSS/jquery-confirm.css?v=1.0" rel="stylesheet" />
<script src="/JS/jquery-3.4.1.js?v=1.0"></script>
<script src="/JS/layui/layui.js?v=1.0"></script>
<script src="/JS/jquery-confirm.js?v=1.0"></script>
</head>
<body>
<div class="layui-fluid">
<div class="layui-card">
<div class="layui-card-body" style="padding: 15px;">
<form class="layui-form">
<div class="layui-card">
<div class="layui-card-body">
<div class="layui-tab layui-tab-card" lay-filter="component-tabs-card">
<div class="layui-tab-content">
<div class="layui-tab-item" style="display:block;">
上传附件
<div class="layui-upload">
<button type="button" class="layui-btn" id="multiple_img_upload">多图片上传</button>
<blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px; ">
预览:
<div class="layui-upload-list" id="div-slide_show"></div>
</blockquote>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="layui-form-item layui-layout-admin">
<div class="layui-input-block">
<div class="layui-footer" style="left: 0; height:66px;">
<button type="button" class="layui-btn sim_btn">提交</button>
<input type="button" id="btnReset" class="layui-btn layui-btn-primary" value="重置" />
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<input type="hidden" name="imgs" class="multiple_show_img" value="" /><%--用于保存多图上传的资源数组--%>
<script type="text/javascript">
//这里一定要设置全局变量,不然下面用的时候,未定义
var multiple_images = [];
var layer, form, laypage, laydate, upload, layedit, indexs, indexsMan, element;
$(function () {
layui.use(['form', 'layedit', 'upload'], function () {
layedit = layui.layedit,
form = layui.form,
upload = layui.upload;
//多图片上传
upload.render({
elem: '#multiple_img_upload'
, url: "/ASHX/SetImg.ashx?actionMore=MoreIMG"
, multiple: true
, before: function (obj) {
var files = obj.pushFile(); //将每次选择的文件追加到文件队列
//var len = getJsonLength(files);
var fileAllNum = 10;//允许每次上传附件的数量
var yishangchuan = $('.multiple_show_img').val();//已经上传完的图片的路径集合,多个以,号分隔
var arrImgNum = 0;//计算出共几张图
if (yishangchuan != "") {
if (yishangchuan.indexOf(",") > 0) {//如果有至少2张图片
arrImgNum = yishangchuan.split(',').length;//计算出共几张图
}
}
//arrImgNum = arrImgNum == arrImgNum ? 2 : arrImgNum;
//alert(arrImgNum);
//alert(len);
//alert(fileAllNum);
if (arrImgNum < fileAllNum) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#div-slide_show').append('<img src="' + result + '" id="' + file.name + '" name="' + file.name + '" alt="' + file.name + '" title="点击删除" class="layui-upload-img" style="width: 100px;height: 100px;" onclick="delMultipleImgs(this)" onmouseover="imgover(this)" onmouseout="imgout(this)" /> ')
delete files[index];//删除列表中已经上传过的对应的文件,一般在某个事件中使用;防止重复上次预览的数据进行的提交问题。
});
}
else {
layer.msg("上传文件最大不允许超过" + fileAllNum + "个");
return false;
}
}
, done: function (res) {
//如果上传成功
//alert(index);
if (res.State == true) {
//追加图片成功追加文件名至图片容器1647508248937-0 1647508263902-0 1647508248937-0
//alert(res.Data);
multiple_images.push(res.Data);
$('.multiple_show_img').val(multiple_images);//把多选择的图片的地址统一放这里
//$('.multiple_show_img').val("");
//multiple_images = [];
//delete this.files[index];
} else {
//提示信息
layer.msg(res.Message);
}
}
});
//多图片上传
});//对应layui.use(['index', 'layer', 'form', 'laypage', 'laydate', 'upload', 'jquery', 'layedit'], function () {
//提交表单
$("body").on("click", ".sim_btn", function () {
SaveData();
});
});//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {//对应$(function () {
function SaveData() {//
/上传附件开始/
var uploadFiles = $('.multiple_show_img').val();//把上传附件多选择的图片的地址统一放这里
alert(uploadFiles);
return false;
/上传附件结束/
//if (names == "") {
// errorMsg = "请输入姓名";
//}
//alert(errorMsg);
//return false;
if (errorMsg != "") {
layer.msg(errorMsg, { icon: 7 });
return false;
} else {
loadIndex = layer.load(0);
var url = "/ClinicalControl/Case_ADD.aspx";
var data = {
'action': 'SaveData'
, 'id': id
, 'uploadFiles': uploadFiles
, 'updateCRIDMan': updateCRIDMan
//, 'test': test
//, 'test': test
}
$.ajax({//
type: "POST",
url: url,
dataType: "JSON",
data: data,
success: function (result) {
if (result.State) {
layer.close(loadIndex);
if (result.Data != "") {
layer.msg(result.Data, { icon: 7 });
}
else {
layer.msg("操作成功", { icon: 6 });
}
setTimeout(closeRefresh, 1000);//关闭当前iframe,刷新指定iframe
}
else {
layer.msg(result.Data, { icon: 7 });
}
}, complete: function (result) {
layer.close(loadIndex);
}
});
}
}
//单击图片删除图片 【注册全局函数】
function delMultipleImgs(this_img) {
$.confirm({
title: '提示',
content: '确定要删除吗?',
confirm: function () {
//获取下标
var subscript = $("#div-slide_show img").index(this_img);
//删除图片
this_img.remove();
//删除数组
multiple_images.splice(subscript, 1);
//重新排序
multiple_images.sort();
$('.multiple_show_img').val(multiple_images);
},
cancel: function () {
layer.msg("操作取消", { icon: 6 });
}
});
//返回
return;
}
//上传附件鼠标悬停提示框
function openMsg01(tempid) {
subtips01 = layer.tips('点击图片删除', '#div-slide_show', { tips: [1, '#ff6700'], time: 30000 });
}
//鼠标悬停提示框
function imgover(img) {
openMsg01("");
}
function imgout(img) {
layer.close(subtips01);
}
</script>
</body>
</html>
/ASHX/SetImg.ashx文件
using Common;
using Model;
using System;
using System.Drawing;
using System.IO;
using System.Web;
namespace MyProject.ASHX
{
/// <summary>
/// SetImg 的摘要说明
/// </summary>
public class SetImg : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string action = "";
string actionMore = "";
context.Response.ContentType = "text/plain";
if (context.Request.Form["action"]!=null)
{
action = context.Request.Form["action"].ToString();//AJAX传参
}
if (context.Request["actionMore"] != null)
{
actionMore = context.Request["actionMore"].ToString();//URL传参
}
switch (action)
{
case "ConvertIMG":
ConvertIMG(context);
break;
default:
break;
}
switch (actionMore)//多图上传
{
case "MoreIMG":
MoreIMG(context);
break;
default:
break;
}
}
/// <summary>
/// 单张图片上传
/// </summary>
/// <param name="context"></param>
public void ConvertIMG(HttpContext context)
{
string imgurl = context.Request.Form["imgurl"].ToString();
string strFilePath = "";
string strReturnFilePath = "";//返回前端的路径,用于存入SQL
string imgname = "";
if (imgurl.IndexOf("data:image") >= 0)
{
string base64 = imgurl.Split(',')[1];//规范化,逗号前面的是标识符,用于说明原图片的名字和格式
string path = context.Server.MapPath("/");//获取网站的根路径
string strRand = PublicHelper.RanStr(10, true);
string strSuffix = ".jpg"; //文件的后缀名根据实际情况
strReturnFilePath = "\\UploadFile\\" + System.DateTime.Now.Year.ToString() + "\\" + System.DateTime.Now.Month.ToString() + "\\" + System.DateTime.Now.Day.ToString() + "\\";
string strPath = path + strReturnFilePath;//在本地硬盘的绝对路径
imgname = strRand + strSuffix;
if (!System.IO.Directory.Exists(strPath))
{
System.IO.Directory.CreateDirectory(strPath);
}
//string local = "UploadFile\\" + System.DateTime.Now.Year.ToString() + "\\" + System.DateTime.Now.Month.ToString() + "\\" + System.DateTime.Now.Day.ToString() + "\\";
//strFilePath = "/UploadFile/" + DateTime.Now.ToString("yyyyMMdd") + strRand + strSuffix;
strFilePath = strPath.Trim().Replace("\\", "/");
strReturnFilePath = strReturnFilePath.Trim().Replace("\\", "/") + imgname;
MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64));
Bitmap bit = new Bitmap(stream);
bit.Save(strPath + imgname);//保存图片到本地
}
ResultInfo resultInfo = new ResultInfo() { State = false };
if (strFilePath != "")
{
resultInfo.Data = strReturnFilePath;
resultInfo.State = true;
}
string resultJson = JsonHelper.ObjectToJSON(resultInfo);
context.Response.Write(resultJson);
context.Response.End();
}
/// <summary>
/// 多张图片上传
/// </summary>
/// <param name="context"></param>
public void MoreIMG(HttpContext context)
{
string strFilePath = "";
if (context.Request.Files.Count > 0)
{
//HttpPostedFile f = context.Request.Files[0];
//f.SaveAs(context.Server.MapPath(f.FileName));
ResultInfo resultInfo = new ResultInfo() { State = false };
int isCheck = 0;//上传附件是否通过验证
var file = context.Request.Files[0];
string extension = System.IO.Path.GetExtension(file.FileName);//获取文件后缀名FileSize
string strFileExtension = PublicHelper.GetValue("FileExtension");//配置文件允许上传的附件类型
string strFileSize = PublicHelper.GetValue("FileSize");//配置文件允许上传的附件类型
if (strFileExtension.IndexOf(extension.ToLower()) < 0)
{
isCheck = 1;
resultInfo.Message = "不支持此附件类型";
}
if (file.ContentLength > Convert.ToInt32(strFileSize))
{
isCheck = 1;
resultInfo.Message = "上传附件过大";
}
if (isCheck == 0)
{
//定义本地路径位置
string local = "UploadFile\\" + System.DateTime.Now.Year.ToString() + "\\" + System.DateTime.Now.Month.ToString() + "\\" + System.DateTime.Now.Day.ToString() + "\\";
//string filePathName = string.Empty;
string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, local);
//var tmpName = HttpContext.Current.Server.MapPath("~/UploadFile/" + strCFID + "/" + System.DateTime.Now.ToString("yyyyMMdd") + "/");
//var tmp = file.FileName;
//var tmpIndex = 0;
//不带路径的最终文件名
string strRand = PublicHelper.RanStr(10, true);
string filePathName = strRand + PublicHelper.FilterSQL(file.FileName);//过滤文件名中的SQL敏感字符
if (!System.IO.Directory.Exists(localPath))
{
System.IO.Directory.CreateDirectory(localPath);
}
//if (System.IO.Directory.Exists(localPath))
//{
// string a1 = "";
//}
//else
//{
// System.IO.Directory.CreateDirectory(localPath);
//}
string localURL = Path.Combine(local, filePathName);
file.SaveAs(Path.Combine(localPath, filePathName)); //保存图片(文件夹)
resultInfo.Data = "/" + localURL.Trim().Replace("\\", "/");
resultInfo.State = true;
resultInfo.Message = "";
}
string resultJson = JsonHelper.ObjectToJSON(resultInfo);
context.Response.Write(resultJson);
context.Response.End();
}
//string imgurl = context.Request.Form["imgurl"].ToString();
//if (imgurl.IndexOf("data:image") >= 0)
//{
// string base64 = imgurl.Split(',')[1];//规范化,逗号前面的是标识符,用于说明原图片的名字和格式
// string path = context.Server.MapPath("/");//获取网站的根路径
// string strRand = PublicHelper.RanStr(10, true);
// string strSuffix = ".jpg"; //文件的后缀名根据实际情况
// string strPath = path + "\\UploadFile\\" + DateTime.Now.ToString("yyyyMMdd") + strRand + strSuffix;
// strFilePath = "/UploadFile/" + DateTime.Now.ToString("yyyyMMdd") + strRand + strSuffix;
// MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64));
// Bitmap bit = new Bitmap(stream);
// bit.Save(strPath);//保存图片到本地
//}
//ResultInfo resultInfo = new ResultInfo() { State = false };
//if (strFilePath != "")
//{
// resultInfo.Data = strFilePath;
// resultInfo.State = true;
//}
//string resultJson = JsonHelper.ObjectToJSON(resultInfo);
//context.Response.Write(resultJson);
//context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
PublicHelper.RanStr(10, true);方法
/// <summary>
/// 获取随机字符串
/// </summary>
/// <param name="Length">生成长度</param>
/// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
/// <returns></returns>
public static string RanStr(int Length, bool Sleep)
{
if (Sleep)
System.Threading.Thread.Sleep(3);
char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
string result = "";
int n = Pattern.Length;
System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < Length; i++)
{
int rnd = random.Next(0, n);
result += Pattern[rnd];
}
return result;
}
PublicHelper.FilterSQL(file.FileName);文章来源:https://www.toymoban.com/news/detail-566972.html
/// <summary>
/// 后台过滤SQL关键字
/// </summary>
/// <param name="str">参数SQL语句</param>
/// <returns></returns>
public static string FilterSQL(string str)
{
//string filterSQL = "'|and|exec|insert|select|delete|update|count | *|%| chr | mid | master | truncate | char | declare |;| or | -| + | ,";
string filterSQL = "exec|insert|delete|update|count|*|chr|mid|master|truncate|char|declare|;";
string[] strArray = filterSQL.Split('|');
for (int i = 0; i < strArray.Length; i++)
{
if (str.IndexOf(strArray[i]) >= 0)
{
str = str.Replace(strArray[i], "");
}
}
return str;
}
配置文件文章来源地址https://www.toymoban.com/news/detail-566972.html
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<!--允许上传的附件类型-->
<add key="FileExtension" value=".jpg.jpeg.gif.png.bmp" />
<!--允许每次上传附件的大小,以byte为单位,1048576是一M。-->
<add key="FileSize" value="10485760" />
<!--允许批量上传附件的数量-->
<add key="FileAllNum" value="3" />
</appSettings>
到了这里,关于layui选择多张图片上传多图上传到服务器保存的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!