多圖上傳在一些特殊的需求中我們經(jīng)常會遇到,其實多圖上傳的原理大家都有各自的見解。對于Layui多圖上傳和我之前所說的通過js獲取文本框中的文件數(shù)組遍歷提交的原理一樣,只不過是Layui中的upload.render方法已經(jīng)幫我們封裝好了,我們只管調(diào)用即可,也就是說你選中了幾張圖片,那么將會向后臺請求與圖片張數(shù)相同的次數(shù),即為遍歷提交的方式。
前端:
<%@ 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; ">
預(yù)覽:
<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="" /><%--用于保存多圖上傳的資源數(shù)組--%>
<script type="text/javascript">
//這里一定要設(shè)置全局變量,不然下面用的時候,未定義
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;//允許每次上傳附件的數(shù)量
var yishangchuan = $('.multiple_show_img').val();//已經(jīng)上傳完的圖片的路徑集合,多個以,號分隔
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) {
//預(yù)讀本地文件示例,不支持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];//刪除列表中已經(jīng)上傳過的對應(yīng)的文件,一般在某個事件中使用;防止重復(fù)上次預(yù)覽的數(shù)據(jù)進(jìn)行的提交問題。
});
}
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);//把多選擇的圖片的地址統(tǒng)一放這里
//$('.multiple_show_img').val("");
//multiple_images = [];
//delete this.files[index];
} else {
//提示信息
layer.msg(res.Message);
}
}
});
//多圖片上傳
});//對應(yīng)layui.use(['index', 'layer', 'form', 'laypage', 'laydate', 'upload', 'jquery', 'layedit'], function () {
//提交表單
$("body").on("click", ".sim_btn", function () {
SaveData();
});
});//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {//對應(yīng)$(function () {
function SaveData() {//
/上傳附件開始/
var uploadFiles = $('.multiple_show_img').val();//把上傳附件多選擇的圖片的地址統(tǒng)一放這里
alert(uploadFiles);
return false;
/上傳附件結(jié)束/
//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);//關(guān)閉當(dāng)前iframe,刷新指定iframe
}
else {
layer.msg(result.Data, { icon: 7 });
}
}, complete: function (result) {
layer.close(loadIndex);
}
});
}
}
//單擊圖片刪除圖片 【注冊全局函數(shù)】
function delMultipleImgs(this_img) {
$.confirm({
title: '提示',
content: '確定要刪除嗎?',
confirm: function () {
//獲取下標(biāo)
var subscript = $("#div-slide_show img").index(this_img);
//刪除圖片
this_img.remove();
//刪除數(shù)組
multiple_images.splice(subscript, 1);
//重新排序
multiple_images.sort();
$('.multiple_show_img').val(multiple_images);
},
cancel: function () {
layer.msg("操作取消", { icon: 6 });
}
});
//返回
return;
}
//上傳附件鼠標(biāo)懸停提示框
function openMsg01(tempid) {
subtips01 = layer.tips('點擊圖片刪除', '#div-slide_show', { tips: [1, '#ff6700'], time: 30000 });
}
//鼠標(biāo)懸停提示框
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];//規(guī)范化,逗號前面的是標(biāo)識符,用于說明原圖片的名字和格式
string path = context.Server.MapPath("/");//獲取網(wǎng)站的根路徑
string strRand = PublicHelper.RanStr(10, true);
string strSuffix = ".jpg"; //文件的后綴名根據(jù)實際情況
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];//規(guī)范化,逗號前面的是標(biāo)識符,用于說明原圖片的名字和格式
// string path = context.Server.MapPath("/");//獲取網(wǎng)站的根路徑
// string strRand = PublicHelper.RanStr(10, true);
// string strSuffix = ".jpg"; //文件的后綴名根據(jù)實際情況
// 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">是否要在生成前將當(dāng)前線程阻止以避免重復(fù)</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);文章來源:http://www.zghlxwxcb.cn/news/detail-566972.html
/// <summary>
/// 后臺過濾SQL關(guān)鍵字
/// </summary>
/// <param name="str">參數(shù)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;
}
配置文件文章來源地址http://www.zghlxwxcb.cn/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" />
<!--允許批量上傳附件的數(shù)量-->
<add key="FileAllNum" value="3" />
</appSettings>
到了這里,關(guān)于layui選擇多張圖片上傳多圖上傳到服務(wù)器保存的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!