基于vue+axios+lrz.js微信端图片压缩上传方法

2020-06-14 06:21:02易采站长站整理

}
}
}

// 添加参数
rst.formData.append('folder', this.folder) // 保存的文件夹
rst.formData.append('base64', rst.base64)
// 触发上传
xhr.send(rst.formData)

return rst
})
},
// 移除图片
remove () {
this.imageUrl = ''
}
}
}
</script>

<style lang="less" scoped>
.imgUploader {
margin-top: 0.5rem;
.file-item {
float: left;
position: relative;
width: 100px;
text-align: center;
left: 2rem;
img {
width: 100px;
height: 100px;
border: 1px solid #ececec;
}
.file-remove {
position: absolute;
right: 0px;
top: 4px;
width: 14px;
height: 14px;
color: white;
cursor: pointer;
line-height: 12px;
border-radius: 100%;
transform: rotate(45deg);
background: rgba(0, 0, 0, 0.5);
}

&:hover .file-remove {
display: inline;
}
.file-name {
margin: 0;
height: 40px;
word-break: break-all;
font-size: 14px;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
}
.add {
width: 100px;
height: 100px;
float: left;
text-align: center;
line-height: 100px;
font-size: 30px;
cursor: pointer;
border: 1px dashed #40c2da;
color: #40c2da;
position: relative;
background: #ffffff;
.icon {
font-size: 1.4rem;
color: #7dd2d9;
vertical-align: -0.25rem;
}
.text {
font-size: 1.2rem;
color: #7dd2d9;
vertical-align: 0.25rem;
}
}
}
input[type="file"] {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
border: 1px solid #000;
opacity: 0;
}
</style>

后端图片存储处理

后端api对图片的处理,是必不可少的环节,需要将前端提交过来的base64字符串转换成图片格式,并存放至指定的文件夹,接口返回图片的Url路径。各项目后端对图片的处理逻辑都不一致,以下方案仅供参考(我们使用asp.net MVC 构建了独立的文件存储站点)。

其核心源码,如下:


/// <summary>
/// 图片文件base64上传
/// </summary>
/// <param name="folder">对应文件夹位置</param>
/// <param name="base64">图片文件base64字符串</param>
/// <returns></returns>
public ActionResult Base64FileUpload(string folder, string base64)
{
var context = System.Web.HttpContext.Current;
context.Response.ClearContent();
// 因为前端调用时,需要做跨域处理