blog.admin net8发布二级目录,及图片上传路径处理
1、发布二级目录,修改以下配置,及对应的二级目录名跟配置的一致
2、图片上传
a、修改后台api代码imgController.cs
public async Task<MessageModel<string>> InsertPicture([FromForm]UploadFileDto dto) { if (dto.file == null || !dto.file.Any()) return Failed("请选择上传的文件。"); //格式限制 var allowType = new string[] { "image/jpg", "image/png", "image/jpeg" }; var allowedFile = dto.file.Where(c => allowType.Contains(c.ContentType)); if (!allowedFile.Any()) return Failed("图片格式错误"); if (allowedFile.Sum(c => c.Length) > 1024 * 1024 * 4) return Failed("图片过大"); string foldername = "images"; string folderpath = Path.Combine(_env.WebRootPath, foldername); string filePaths = ""; if (!Directory.Exists(folderpath)) { Directory.CreateDirectory(folderpath); } foreach (var file in allowedFile) { string strpath = Path.Combine(foldername, DateTime.Now.ToString("MMddHHmmss") + Path.GetFileName(file.FileName)); var path = Path.Combine(_env.WebRootPath, strpath); filePaths = (string.IsNullOrEmpty(filePaths) ? "" : ",") + strpath; using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { await file.CopyToAsync(stream); } } var excludeFiles = dto.file.Except(allowedFile); if (excludeFiles.Any()) { var infoMsg = $"{string.Join('、', excludeFiles.Select(c => c.FileName))} 图片格式错误"; return Success<string>(null, infoMsg); } return Success<string>(filePaths, "上传成功"); }
b、修改前端api.js代码,导出后台api配置地址
let base = 'http://localhost:8081'; export const BaseApiUrl =base;
c、在前端vue项目需要用到上传图片的页面修改以下代码
1、引用后台API地址
import {BaseApiUrl} from '../../api/api' //引用后台API地址
2、data里面定义一个上传api url
data() {
return {
actionUrl:BaseApiUrl+"/images/Upload/Pic",
}
}
3、设置上传url
<el-form-item label="头像">
<el-upload
class="avatar-uploader"
:action="actionUrl"
:show-file-list="false"
:headers="token"
:data="ruleForm"
:on-success="handleAvatarSuccessAdd"
:before-upload="beforeAvatarUploadAdd"
>
<img v-if="addForm.Photo" :src="addForm.Photo" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon plus-sign"></i>
</el-upload>
</el-form-item>
4、修改上传成功回调函数
handleAvatarSuccess(res, file) {
console.log(res);
this.editForm.Photo = BaseApiUrl + "/" + res.response;
},