实现目标。点击图片上传头像
效果图
前端部分图片上传关键代码
csharp
<div class="avatar-wrap">
<el-image
style="width: 154px; height: 154px"
:src="form.headPic"
:fit="fit"
/>
</div>
<div class="upload-box">
<el-upload
class="avatar-uploader"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:http-request="customUpload"
>
<!-- 自定义上传按钮 -->
<div class="custom-upload-btn">
<span>更换头像</span>
</div>
</el-upload>
</div>
上传js部分
csharp
<script>
import { ref, reactive, onMounted } from "vue";
import { uploadAvatar } from "../../api/auth";
import { ElMessage } from "element-plus";
export default {
setup() {
const fit = ref("cover");
const form = reactive({
userId: 0,
headPic:
"https://ww1.sinaimg.cn/mw690/9516662fgy1hct88xfrd9j20k00k0dho.jpg",
userName: "",
phone: "",
});
// 上传成功后的处理函数
const handleAvatarSuccess = (response, file) => {
};
// 上传之前的检查函数
const beforeAvatarUpload = (file) => {
const isJPG = file.type === "image/jpeg" || file.type === "image/png";
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
}
return isJPG && isLt2M;
};
const customUpload = async (options) => {
const { file, onSuccess, onError } = options;
const formData = new FormData();
formData.append("file", file);
try {
const response = await uploadAvatar(formData);
onSuccess(response.data); // 上传成功时的回调
} catch (error) {
onError(error); // 上传失败时的回调
ElMessage.error("上传失败,请重试");
}
};
return {
fit,
form,
customUpload,
beforeAvatarUpload,
handleAvatarSuccess,
};
},
};
auth.js
csharp
//头像上传
export function uploadAvatar(info) {
return request({
url: "/Pictrue/TestForm",
headers: {
"Content-Type": "multipart/form-data",
},
method: "post",
data: info,
});
}
有问题的后台【接口本身没有问题,小程序上传也使用的这个接口不会有问题】
csharp
public async Task<Result> PicUploadToUrl()
{
try
{
var files = Request.Form.Files;
if (files.Count > 0)
{
List<string> urlList = new List<string>();
foreach (var item in files)
{
string[] arr = item.FileName.Split('.'); //得到当前的图片对象
string format = arr[arr.Length - 1]; //得到图片后缀名称
var rst = await pictureService.PicUploadToUrl(item.OpenReadStream(), item.FileName, format);
if (rst.IsSuccess)
urlList.Add(rst.Message);
else
return rst;
}
GC.Collect();
return Result.NewSuccess(urlList);
}
return Result.NewError(message: "图片上传失败");
}
catch (Exception ex)
{
NLogUtil.Default.Log(LogLevel.Error, "PicUploadToUrl.上传错误:" + ex.Message);
return Result.NewError(message: "图片上传失败");
}
}
解决办法,改变接收的方式
csharp
[HttpPost]
[DisableRequestSizeLimit]
public async Task<Result> TestForm([FromForm] IFormCollection formData)
{
try
{
var files = formData.Files;
if (files.Count > 0)
{
List<string> urlList = new List<string>();
foreach (var item in files)
{
string[] arr = item.FileName.Split('.'); //得到当前的图片对象
string format = arr[arr.Length - 1]; //得到图片后缀名称
var rst = await pictureService.PicUploadToUrl(item.OpenReadStream(), item.FileName, format);
if (rst.IsSuccess)
urlList.Add(rst.Message);
else
return rst;
}
GC.Collect();
return Result.NewSuccess(urlList);
}
return Result.NewError(message: "图片上传失败");
}
catch (Exception ex)
{
NLogUtil.Default.Log(LogLevel.Error, "PicUploadToUrl.上传错误:" + ex.Message);
return Result.NewError(message: "图片上传失败");
}
}
注意startup.cs中的配置。这里根据实际情况进行配置需要的即可
csharp
public void ConfigureServices(IServiceCollection services)
{
//设置接收文件长度的最大值。
services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.ValueCountLimit = int.MaxValue;
x.MultipartBodyLengthLimit = int.MaxValue;//2147483647;
x.MultipartHeadersCountLimit = int.MaxValue;
x.MultipartBoundaryLengthLimit = int.MaxValue;
x.BufferBodyLengthLimit = long.MaxValue;
x.BufferBody = true;
x.KeyLengthLimit = int.MaxValue;
x.MultipartHeadersLengthLimit = int.MaxValue;
});
}