首页 VueJS Vue+.NETAPI上传文件图片

Vue+.NETAPI上传文件图片

作者:胡同里的砖头 围观群众:219 更新于:2024-04-10

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>
方法如下:
 
// 上传之前
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)
}
.NET 接口
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】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8