关于layui图片/文件上传

Posted yagamilight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于layui图片/文件上传相关的知识,希望对你有一定的参考价值。

一:常规使用   普通文件上传 (传入服务器一张图片)

1.前台代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="../layui/css/layui.css" rel="stylesheet" />
<title></title>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>常规使用:普通图片上传</legend>
</fieldset>

<div class="layui-upload">
<button type="button" class="layui-btn" id="test1">上传图片</button>
<div class="layui-upload-list">
<img class="layui-upload-img" id="demo1">
<p id="demoText"></p>
</div>
</div>
<script src="../layui/jquery-3.3.1.js"></script>
<script src="../layui/layui.js"></script>
<script>
layui.use(‘upload‘, function () {
var upload = layui.upload;
//普通图片上传
var uploadInst = upload.render({
//这里url就是 你上传图片的接口
//before是上传图片之前的回调,就是将图片展示出来啦
//done就是完成图片上传后的回调
//error就是上传发生错误的回调,比如你要上传的服务器不存在要保存图片的文件夹就会触发error回调
elem: ‘#test1‘
, url: ‘/UploadFile/ashxjiekou/upload.ashx‘
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$(‘#demo1‘).attr(‘src‘, result);
});

}
, done: function (res) {
//这里回调函数的参数res就是接口返回的数据
//alert(JSON.stringify(res.data.src))
//如果上传失败
if (res.code > 0) {
return layer.msg(‘上传失败‘);
}
layer.msg(‘上传成功‘)
}
, error: function () {
//演示失败状态,并实现重传
var demoText = $(‘#demoText‘);
demoText.html(‘<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>‘);
demoText.find(‘.demo-reload‘).on(‘click‘, function () {
uploadInst.upload();
});
}
});
})
</script>
</body>
</html>

这里前台代码 都是完整的 考的你的编辑器就可以用了 当然引用的jquery 和 layui路径要改成你自己相应的路径

2.接下来我们看后台ashx接口,后台也考个完整的把 看起来量多(但其实没什么好说的)

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace UploadLearning.UploadFile.ashxjiekou
{
/// <summary>
/// upload 的摘要说明
/// </summary>
public class upload : IHttpHandler
{
JObject json = new JObject();
JObject rtn = new JObject();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
HttpFileCollection files = context.Request.Files;
string path = "/upImage";
checkDir(path);
if (files.Count > 0)
{
files[0].SaveAs(context.Server.MapPath("/upImage/" + files[0].FileName + ".jpg"));
//context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "ok" }, Newtonsoft.Json.Formatting.Indented));
rtn.Add("src", "upImage/" + files[0].FileName + ".jpg");
json.Add(new JProperty("code", 0));
json.Add(new JProperty("msg", ""));
json.Add(new JProperty("data", rtn));
}
context.Response.Write(json.ToString());
context.Response.End();
}

public bool IsReusable
{
get
{
return false;
}
}


#region 检查指定目录是否存在,如不存在则创建
/// <summary>
/// 检查指定目录是否存在,如不存在则创建
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public void checkDir(string url)
{
if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(url)) == false)
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(url));
}
}
#endregion
}
}

3.普通图片上传总结:

普通图片上传就这样了 ,其中后台用到了类HttpFileCollection,这个类用于获取浏览器上传的文件集合。。。请注意是集合。其它就没什么注意的啦

二 :上传多张图片

1.多图片上传前台代码 :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="../layui/css/layui.css" rel="stylesheet" />
<script src="../layui/jquery-3.3.1.js"></script>
<title></title>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>常规使用:普通图片上传</legend>
</fieldset>

<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>上传多张图片</legend>
</fieldset>

<div class="layui-upload">
<button type="button" class="layui-btn" id="test2">多图片上传</button>
<blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
预览图:
<div class="layui-upload-list" id="demo2"></div>
</blockquote>
</div>

<div class="layui-upload">
<button type="button" class="layui-btn" id="test1">上传图片</button>
<div class="layui-upload-list">
<img class="layui-upload-img" id="demo1">
<p id="demoText"></p>
</div>
</div>
<script src="../layui/jquery-3.3.1.js"></script>
<script src="../layui/layui.js"></script>
<script>
layui.use(‘upload‘, function () {
var upload = layui.upload;
//普通图片上传
var uploadInst = upload.render({
//这里url就是 你上传图片的接口
//before是上传图片之前的回调,就是将图片展示出来啦
//done就是完成图片上传后的回调
//error就是上传发生错误的回调,比如你要上传的服务器不存在要保存图片的文件夹就会触发error回调
elem: ‘#test1‘
, url: ‘/UploadFile/ashxjiekou/upload.ashx‘
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$(‘#demo1‘).attr(‘src‘, result);
});

}
, done: function (res) {
//这里回调函数的参数res就是接口返回的数据
//alert(JSON.stringify(res.data.src))
//如果上传失败
if (res.code > 0) {
return layer.msg(‘上传失败‘);
}
layer.msg(‘上传成功‘)
}
, error: function () {
//演示失败状态,并实现重传
var demoText = $(‘#demoText‘);
demoText.html(‘<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>‘);
demoText.find(‘.demo-reload‘).on(‘click‘, function () {
uploadInst.upload();
});
}
});
var s = "";
//多图片上传
upload.render({
elem: ‘#test2‘
, url: ‘/UploadFile/ashxjiekou/tupianshangchuanduo.ashx‘
, multiple: true
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$(‘#demo2‘).append(‘<img src="‘ + result + ‘" alt="‘ + file.name + ‘" class="layui-upload-img">‘)
});
}
, done: function (res) {
//上传完毕
alert(JSON.stringify(res));
if (s == "") {
s = JSON.stringify(res.data.src);
}
else {
s = s + "," + JSON.stringify(res.data.src);
}
alert(s)
}
});

})
</script>
</body>
</html>

2.多图片上传后台接口

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UploadLearning.UploadFile.ashxjiekou
{
/// <summary>
/// tupianshangchuanduo 的摘要说明
/// </summary>
public class tupianshangchuanduo : IHttpHandler
{
JObject json = new JObject();
JObject rtn = new JObject();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
HttpFileCollection files = context.Request.Files;
string path = "/tupianshangchuanduo";
checkDir(path);
string s = string.Empty;
if (files.Count > 0)
{
files[0].SaveAs(context.Server.MapPath("/tupianshangchuanduo/" + files[0].FileName + ".jpg"));
//context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "ok" }, Newtonsoft.Json.Formatting.Indented));
rtn.Add("src", "upImage/" + files[0].FileName + ".jpg");
json.Add(new JProperty("code", 0));
json.Add(new JProperty("msg", ""));
json.Add(new JProperty("data", rtn));
}
context.Response.Write(json.ToString());
context.Response.End();
}

public bool IsReusable
{
get
{
return false;
}
}

#region 检查指定目录是否存在,如不存在则创建
/// <summary>
/// 检查指定目录是否存在,如不存在则创建
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public void checkDir(string url)
{
if (System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(url)) == false)
{
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(url));
}
}
#endregion
}
}

3.多图片上传总结:

多图片上传这个接口的调用要注意,其实他是多个进程一起一起工作的 所以说我们的HttpFileCollection类对象并没有被遍历  我最开始的思考就是多图片是一次传了很多上来在通过遍历实现保存,但并不是这样。

三:高级应用:制作一个多文件列表

1.多文件上传html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="../layui/css/layui.css" rel="stylesheet" />
<script src="../layui/jquery-3.3.1.js"></script>
<title></title>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>常规使用:普通图片上传</legend>
</fieldset>

<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>上传多张图片</legend>
</fieldset>

<div class="layui-upload">
<button type="button" class="layui-btn" id="test2">多图片上传</button>
<blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
预览图:
<div class="layui-upload-list" id="demo2"></div>
</blockquote>
</div>

<div class="layui-upload">
<button type="button" class="layui-btn" id="test1">上传图片</button>
<div class="layui-upload-list">
<img class="layui-upload-img" id="demo1">
<p id="demoText"></p>
</div>
</div>


<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>高级应用:制作一个多文件列表</legend>
</fieldset>

<div class="layui-upload">
<button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button>
<div class="layui-upload-list">
<table class="layui-table">
<thead>
<tr>
<th>文件名</th>
<th>大小</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody id="demoList"></tbody>
</table>
</div>
<button type="button" class="layui-btn" id="testListAction">开始上传</button>
</div>


<script src="../layui/jquery-3.3.1.js"></script>
<script src="../layui/layui.js"></script>
<script>
layui.use(‘upload‘, function () {
var upload = layui.upload;
//普通图片上传
var uploadInst = upload.render({
//这里url就是 你上传图片的接口
//before是上传图片之前的回调,就是将图片展示出来啦
//done就是完成图片上传后的回调
//error就是上传发生错误的回调,比如你要上传的服务器不存在要保存图片的文件夹就会触发error回调
elem: ‘#test1‘
, url: ‘/UploadFile/ashxjiekou/upload.ashx‘
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$(‘#demo1‘).attr(‘src‘, result);
});

}
, done: function (res) {
//这里回调函数的参数res就是接口返回的数据
//alert(JSON.stringify(res.data.src))
//如果上传失败
if (res.code > 0) {
return layer.msg(‘上传失败‘);
}
layer.msg(‘上传成功‘)
}
, error: function () {
//演示失败状态,并实现重传
var demoText = $(‘#demoText‘);
demoText.html(‘<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>‘);
demoText.find(‘.demo-reload‘).on(‘click‘, function () {
uploadInst.upload();
});
}
});
var s = "";
//多图片上传
upload.render({
elem: ‘#test2‘
, url: ‘/UploadFile/ashxjiekou/tupianshangchuanduo.ashx‘
, multiple: true
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$(‘#demo2‘).append(‘<img src="‘ + result + ‘" alt="‘ + file.name + ‘" class="layui-upload-img">‘)
});
}
, done: function (res) {
//上传完毕
alert(JSON.stringify(res));
if (s == "") {
s = JSON.stringify(res.data.src);
}
else {
s = s + "," + JSON.stringify(res.data.src);
}
alert(s)
}
});

 

//多文件列表示例
var demoListView = $(‘#demoList‘)
, uploadListIns = upload.render({
elem: ‘#testList‘
, url: ‘/UploadFile/ashxjiekou/duowenjianList.ashx‘
, accept: ‘file‘
, multiple: true
, auto: false
, bindAction: ‘#testListAction‘
, choose: function (obj) {
var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
//读取本地文件
obj.preview(function (index, file, result) {
var tr = $([‘<tr id="upload-‘ + index + ‘">‘
, ‘<td>‘ + file.name + ‘</td>‘
, ‘<td>‘ + (file.size / 1014).toFixed(1) + ‘kb</td>‘
, ‘<td>等待上传</td>‘
, ‘<td>‘
, ‘<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>‘
, ‘<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>‘
, ‘</td>‘
, ‘</tr>‘].join(‘‘));

//单个重传
tr.find(‘.demo-reload‘).on(‘click‘, function () {
obj.upload(index, file);
});

//删除
tr.find(‘.demo-delete‘).on(‘click‘, function () {
delete files[index]; //删除对应的文件
tr.remove();
uploadListIns.config.elem.next()[0].value = ‘‘; //清空 input file 值,以免删除后出现同名文件不可选
});

demoListView.append(tr);
});
}
, done: function (res, index, upload) {
if (res.code == 0) { //上传成功
var tr = demoListView.find(‘tr#upload-‘ + index)
, tds = tr.children();
tds.eq(2).html(‘<span style="color: #5FB878;">上传成功</span>‘);
tds.eq(3).html(‘‘); //清空操作
return delete this.files[index]; //删除文件队列已经上传成功的文件
}
this.error(index, upload);
}
, error: function (index, upload) {
var tr = demoListView.find(‘tr#upload-‘ + index)
, tds = tr.children();
tds.eq(2).html(‘<span style="color: #FF5722;">上传失败</span>‘);
tds.eq(3).find(‘.demo-reload‘).removeClass(‘layui-hide‘); //显示重传
}
});

})
</script>
</body>
</html>

2.多文件上传后台接口

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace UploadLearning.UploadFile.ashxjiekou
{
/// <summary>
/// duowenjianList 的摘要说明
/// </summary>
public class duowenjianList : IHttpHandler
{
JObject json = new JObject();
JObject rtn = new JObject();

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
HttpFileCollection files = context.Request.Files;
string path = "/upduowenjianList";
checkDir(path);
if (files.Count > 0)
{
files[0].SaveAs(context.Server.MapPath("/upduowenjianList/" + files[0].FileName + ".jpg"));
//context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "ok" }, Newtonsoft.Json.Formatting.Indented));
rtn.Add("src", "upImage/" + files[0].FileName + ".jpg");
json.Add(new JProperty("code", 0));
json.Add(new JProperty("msg", ""));
json.Add(new JProperty("data", rtn));
}
context.Response.Write(json.ToString());
context.Response.End();
}

public bool IsReusable
{
get
{
return false;
}
}

#region 检查指定目录是否存在,如不存在则创建
/// <summary>
/// 检查指定目录是否存在,如不存在则创建
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public void checkDir(string url)
{
if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(url)) == false)
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(url));
}
}
#endregion
}
}

3.多文件上传总结:其他都大同小异。唯一需要注意的是加入上传的文件太大会发生错误:System.Web.HttpException: 超过了最大请求长度。这是因为asp.net默认限制最大上传文件大小为4096KB,需要修改项目的web.config文件即可解决,可以将最大文件长度设置为你需要的长度如下:

 <httpRuntime targetFramework="4.7.1" maxRequestLength="20240" />

如此 以上问题就可以解决了

 










































































































































































































































































































































































































































































以上是关于关于layui图片/文件上传的主要内容,如果未能解决你的问题,请参考以下文章

layui文件上传回调前对文件类型及大小判断

LayUI上传图片(文件)的时候,上传多张图片(文件)会调用多次接口,而我们想要让上传多个文件的时候只调用一次接口,怎么解决?

LayUI上传图片(文件)的时候,上传多张图片(文件)会调用多次接口,而我们想要让上传多个文件的时候只调用一次接口,怎么解决?

layui多图片怎么按名称顺序上传

layui多图片上传,限制重复图片,限制数量

layui——上传图片,并实现放大预览