Vue上传控件代码
<el-upload方法如下:
class="avatar-uploader"
action="https://localhost:7206/upload/index"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
.NET 接口
// 上传之前
const beforeAvatarUpload = (rawFile) => {
if (rawFile.type !== "image/jpeg"&&rawFile.type !== "image/png"&&rawFile.type !== "image/jpg") {
$baseMessage('图片只能是JPG或PNG格式!','warning',"vab-hey-message-warning");
return;
}
if (rawFile.size / 1024 >500) {
$baseMessage('图片大小不能超过500KB!','warning',"vab-hey-message-warning");
return;
}
};
const handleAvatarSuccess = (res, file) => {
if (file.response.success) {
console.log(JSON.stringify(file))
state.form.a_Avatar = file.response.url
state.a_Avatar = URL.createObjectURL(file.raw)
}
$baseMessage(res.msg, res.icon, res.icon2)
}
using Microsoft.AspNetCore.Mvc;实现效果:
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dal;
using Mod;
using VIPSystem.code;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
namespace VIPSystem.Controllers
{
[ApiController]
[Route("[controller]/[Action]")]
public class UploadController : ControllerBase
{
private readonly IHostingEnvironment _hostingEnvironment;
public UploadController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public async System.Threading.Tasks.Task<IActionResult> Index()
{
IFormFile file = Request.Form.Files[0];
try
{
FileInfo fi = new FileInfo(file.FileName);
string ext = fi.Extension;
var orgFileName = fi.Name;
var newFileName = Guid.NewGuid() + ext;
string savepath = string.Format("wwwroot/file/{0}", DateTime.Now.ToString("yyyyMM"));
var uploads = Path.Combine(_hostingEnvironment.ContentRootPath, savepath);
PageBase.FolderCreate(uploads);
var filePath = Path.Combine(uploads, newFileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
string url = string.Format("{0}/{1}", savepath, newFileName);
var response = new
{
code = 200,
msg = "上传成功",
icon = "success",
icon2 = "vab-hey-message-success",
success = true,
url = url
};
return Ok(response);
}
catch (Exception ex)
{
var response = new
{
code = 0,
msg = "上传失败",
icon = "error",
icon2 = "vab-hey-message-error",
success = false,
};
return Ok(response);
}
}
}
}
- 本文标题: Vue+.NETAPI上传文件图片
- 文章分类:【VueJS】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
- 上一篇:Window系统右下角时间显示秒
- 下一篇: NET6.0 API上传的文件不能访问,无权限