Layui multi image upload function of. Net learning notes

Time:2020-6-19

preface:

We often meet some special needs in multi map upload. In fact, everyone has their own opinions on the principle of multi map upload. For multi graph upload of layui, the principle of traversing and submitting the file array in the text box through JS is the same as I said before, but only in layui upload.render Method has been encapsulated for us. We just call it. That is to say, if you select several pictures, you will request the same number of times to the background as the number of pictures, which is the way to traverse and submit.

Layui file / image style address (official document): https://www.layui.com/demo/upload.html

1、 Introduction Layui.cs and Layui.js :

Need to have the relevant style of layui and JS, non network address in the local project

 <link rel=”stylesheet” href=”//res.layui.com/layui/dist/css/layui.css” rel=”external nofollow”   media=”all”>

 <script src=”//res.layui.com/layui/dist/layui.js” charset=”utf-8″></script>

Of course, if you need a pop-up prompt, you need to introduce Layer.js

2、 Front end code:

a. Code in HTML:

<li>
< H6 > scroll picture: < H6 >
 <div>
< button type = "button" > scroll to upload [three recommended uploads] < button > < button type = "button" onclick = "clearall()" > < I >  < I > < button >
<input type="hidden" name="ScrollingGraph"/>
<blockquote style="margin-top: 10px;">
Preview:
<div></div>
</blockquote>
</div>
</li>

b. Code in JS:

<script>
layui.use('upload',
function () {
var $ = layui.jquery, upload = layui.upload;
//Upload multiple pictures
upload.render({
 elem: '#test2',
 url: '/FileUpload/FileLoad/',
 Multiple: true, // multiple pictures are allowed to be selected
before: function (obj) {
//Pre read local file example, does not support IE8
obj.preview(function (index, file, result) {
$('#demo2').append(
'<img src="' + result + '" alt="' + file.name + '">');
});
},
done: function (res) {
if (res.isSuccess == true) {
layer.msg ("upload succeeded");
var scrollingGraph = $("#ScrollingGraph").val();
if (scrollingGraph == "") {
$("#ScrollingGraph").val(res.path);
} else {
scrollingGraph += ',' + res.path;
$("#ScrollingGraph").val(scrollingGraph);
}
console.log(scrollingGraph);
} else {
return  layer.msg ('upload failed');
}
}
});
});


//Clear all pictures
function clearAll() {
layer.confirm ("are you sure you want to empty all? ", {
icon: 3,
Btn: ["OK", "Cancel"],
yes: function (index) {
$("#demo2").html("");
$("#ScrollingGraph").val("");
layer.close(index);
}
});
}

</script>

3、 The image file stream of the server interface is saved:

1public class FileUploadController : Controller
 2{
 3/// <summary>
///Encapsulate the information needed to verify and process the input data in HTML forms, such as a file made up of fromdata
/// </summary>
///< param name = "context" > femcontext encapsulates the validation and processing of the data entered in the HTML form < / param >
/// <returns></returns>
[HttpPost]
public ActionResult FileLoad(FormContext context)
 {
HttpPostedFileBase httpPostedFileBase =  Request.Files [0]; // get binary image file stream
if (httpPostedFileBase != null)
{
try
{
ControllerContext.HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
ControllerContext.HttpContext.Response.Charset = "UTF-8";

string fileName =  Path.GetFileName ( httpPostedFileBase.FileName ); // original file name
string fileExtension =  Path.GetExtension (filename); // file extension

Byte [] filedata = readfilebytes (httppostedfilebase); // the file stream is converted to binary bytes

String result = savefile (fileextension, filedata); // save the file
if (string.IsNullOrEmpty(result))
{
Return JSON (New {issuccess = false, path = "", errormsg = "upload file failed"});
}

return Json(new { isSuccess = true, path = result });
}
catch (Exception ex)
{
return Json(new { isSuccess = false, path = "" });
}
}
else
{
return Json(new { isSuccess = false, path = "" });
}
}


/// <summary>
///Convert file stream to binary bytes
/// </summary>
///< param name = "filedata" > picture file stream < / param >
/// <returns></returns>
private byte[] ReadFileBytes(HttpPostedFileBase fileData)
{
byte[] data;
using (Stream inputStream = fileData.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
return data;
}

/// <summary>
///Save file
/// </summary>
///< param name = "fileextension" > file extension < / param >
///< param name = "filedata" > image binary information < / param >
/// <returns></returns>
private string SaveFile(string fileExtension, byte[] fileData)
{
string result;
try
{

string saveName =  Guid.NewGuid (). Tostring() + fileextension; // save file name

//Save path after file upload
string basePath = "UploadFile";
string saveDir = DateTime.Now.ToString("yyyy-MM-dd");
string savePath = System.IO.Path.Combine(saveDir, saveName);

string serverDir = System.IO.Path.Combine(Server.MapPath("~/"), basePath, saveDir);
if (!System.IO.Directory.Exists(serverDir))
{
System.IO.Directory.CreateDirectory(serverDir);
}
string fileNme =  System.IO.Path . combine (serverdir, savename); // save the full path of the file
System.IO.File . writeallbytes (filenme, filedata); // writeallbytes creates a new file and writes it according to the corresponding file stream. If it exists, overwrite it
//Return to the complete image saving address
result="/"+basePath + "/" + saveDir + "/" + saveName;
}
catch (Exception)
{
Result = "error occurred";
}
return result;
}
}

4、 Rendering:

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.