一、 视频上传
1、 前端:
<div class="layui-container">
<div class="layui-row">
<div class="layui-col-md6">
<div class="layui-upload">
<button type="button" class="layui-btn" id="uploadVideoBtn">上传视频</button>
</div>
</div>
</div>
</div>
<script>
//视频上传
layui.use('upload', function () {
var upload = layui.upload;
// 执行上传视频
var uploadInst = upload.render({
elem: '#uploadVideoBtn', // 指定上传按钮的容器 ID
url: 'https://localhost:7106/api/RoomType/UploadVideo', // 替换为你实际的视频上传地址
accept: 'video', // 只接受视频文件
size: 30 * 1024, // 设置视频最大大小为30MB,单位为KB
done: function (res) { // 上传成功的回调函数
console.log(res); // 在控制台打印服务器返回的数据
if (res.message === "上传成功") { // 假设服务器返回的状态码为 0 表示上传成功
var videoUrl = res.data; // 假设视频地址存储在 data 字段中
console.log("视频地址:" + videoUrl);
} else {
layer.msg(res.message);
}
},
error: function () { // 上传失败的回调函数
layer.msg("上传失败");
}
});
});
</script>
2、 后端:
private readonly IMediator mediator;
private readonly IWebHostEnvironment environment;
public RoomTypeController(IMediator mediator, IWebHostEnvironment environment)
{
this.mediator = mediator;
this.environment = environment;
}
/// <summary>
/// 视频上传
/// </summary>
/// <returns></returns>
// POST: api/video/upload
[HttpPost]
public async Task<IActionResult> UploadVideo()
{
try
{
var contentLength = HttpContext.Request.ContentLength;
if (contentLength != null && contentLength > 31457280) // 判断请求体是否超过30MB(30 * 1024 * 1024字节)
{
return BadRequest(new { error = "请求体的大小超过了30MB" });
}
var file = Request.Form.Files[0]; // 获取上传的文件
if (file.Length > 0)
{
var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); // 生成唯一的文件名
var filePath = Path.Combine(environment.WebRootPath, "Video", fileName); // 设置保存文件的路径
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream); // 将文件保存到指定路径
}
var videoUrl = Url.Content("~/Video/" + fileName); // 构建视频地址
// 在这里可以进一步处理视频信息,例如将文件路径或其他相关信息保存到数据库中
// 返回上传成功的响应,包含视频地址
return Ok(new { message = "上传成功", data = videoUrl });
}
// 如果没有上传任何文件,返回上传失败的响应
return BadRequest(new { error = "没有选择任何文件" });
}
catch (Exception ex)
{
// 返回上传失败的响应
return StatusCode(500, new { error = "上传失败:" + ex.Message });
}
}
二、 图片上传
1、 前端
<div class="layui-upload">
<button type="button" class="layui-btn" id="ID-upload-demo-btn-2">
<i class="layui-icon layui-icon-upload"></i> 上传图片
</button>
<blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 11px;">
<div class="layui-upload-list" id="upload-demo-preview"></div>
</blockquote>
</div>
<button type="button" class="layui-btn" id="ID-upload-demo-btn">
<i class="layui-icon layui-icon-upload"></i> 单图片上传
</button>
<div style="width: 132px;">
<div class="layui-upload-list">
<img class="layui-upload-img" id="ID-upload-demo-img" style="width: 100%; height: 92px;">
<div id="ID-upload-demo-text"></div>
</div>
<div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo">
<div class="layui-progress-bar" lay-percent=""></div>
</div>
</div>
//图片上传
layui.use(function () {
var upload = layui.upload;
var layer = layui.layer;
var element = layui.element;
var $ = layui.$;
// 单图片上传
var uploadInst = upload.render({
elem: '#ID-upload-demo-btn',
url: 'http://10.31.56.10:9992/api/RoomType/UploadImage', // 替换为你自己的上传接口地址
before: function (obj) {
// 预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#ID-upload-demo-img').attr('src', result); // 图片链接(base64)
});
element.progress('filter-demo', '0%'); // 进度条复位
layer.msg('上传中', { icon: 16, time: 0 });
},
done: function (res) {
// 若上传失败
if (res == "" || res == null) {
return layer.msg('上传失败');
}
// 上传成功,保存图片路径到变量中
vrDisplay = res;
// 上传成功的一些操作
// …
$('#ID-upload-demo-text').html(''); // 置空上传失败的状态
},
error: function () {
// 演示失败状态,并实现重传
var demoText = $('#ID-upload-demo-text');
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();
});
},
// 进度条
progress: function (n, elem, e) {
element.progress('filter-demo', n + '%'); // 可配合 layui 进度条元素使用
if (n == 100) {
layer.msg('上传完毕', { icon: 1 });
}
}
});
// 多图片上传
upload.render({
elem: '#ID-upload-demo-btn-2',
url: 'http://10.31.56.10:9992/api/RoomType/UploadImage', // 此处用的是第三方的 http 请求演示,实际使用时改成您自己的上传接口即可。
multiple: true,
before: function (obj) {
// 预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#upload-demo-preview').append('<img src="' + result + '" alt="' + file.name + '" style="width: 90px; height: 90px;">')
});
},
done: function (res) {
for (var i = 0; i < res.length; i++) {
roomTypePicture.push(res[i]); // 将图片路径添加到 roomTypePicture 数组中
}
console.log(roomTypePicture.toString()) // 打印 roomTypePicture 数组,用于调试
}
});
});
2、 后端
/// <summary>
/// 图片上传
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> UploadImage()
{
var files = Request.Form.Files; // 获取上传的文件集合
if (files == null || files.Count == 0)
{
return BadRequest("没有选择上传的文件");
}
List<string> fileUrls = new List<string>();
foreach (var file in files)
{
var filePath = await UploadImage(file); // 调用封装的上传图片方法
if (filePath != null)
{
fileUrls.Add(filePath);
}
else
{
return BadRequest("文件上传失败");
}
}
// 在此处处理上传成功的逻辑,如将文件路径存储到数据库或返回给客户端等
return Ok(fileUrls); // 返回上传成功的图片路径列表
}
/// <summary>
/// 图片上传
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
private async Task<string> UploadImage(IFormFile file)
{
if (file == null || file.Length == 0)
{
return null;
}
var fileName = file.FileName;
var fileExtension = Path.GetExtension(fileName);
var uniqueFileName = Guid.NewGuid().ToString("N") + fileExtension;
var fileDirectory = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "File");
var filePath = Path.Combine(fileDirectory, uniqueFileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return filePath;
}
标签:function,layui,upload,mvc,file,res,var,上传 From: https://www.cnblogs.com/qibaidao/p/17655964.html