实现多张图片和单张图片上传和删除功能。
前端代码如下:
<style> #app { background-color: white; padding: 15px 15px; } .el-row { margin: 60px 20px; } input[type="file"] { display: none; } .el-form-item__content { display: inline-block; } </style> <div id="app"> <el-button type="primary" icon="el-icon-arrow-left" v-on:click="ReturnGoodsList()">返回</el-button> <el-form ref="form" :model="form" status-icon :rules="rules" label-width="100px;" class="demo-ruleForm"> <el-row> <el-col :span="4"> <el-form-item label="兑换名称:" prop="Name"> <el-input v-model="form.Name"></el-input> </el-form-item> </el-col> <el-col :span="4"> <el-form-item label="所需积分:" prop="RequireScore"> <el-input v-model.number="form.RequireScore"></el-input> </el-form-item> </el-col> <el-col :span="4"> <el-form-item label="每人限额:" prop="PerPersonCount"> <el-input v-model.number="form.PerPersonCount"></el-input> </el-form-item> </el-col> <el-col :span="4"> <el-form-item label="总共份额:" prop="Stock"> <el-input v-model.number="form.Stock"></el-input> </el-form-item> </el-col> <el-col :span="4"> <el-form-item label="价格:" prop="Price"> <el-input v-model="form.Price"></el-input> </el-form-item> </el-col> </el-row> <el-row style="margin-top:20px;"> <el-col :span="1"> <label>商品展示图:</label> </el-col> <el-col :span="23"> <el-upload style="display:inline-block;" action="/api/score-mgr/Score/GoodsUploadImg" list-type="picture-card" :auto-upload="false" :data="getScoreForm()" ref="uploadRef" :limit="4" :multiple="true" :file-list="fileList" :on-remove="removePic" :on-success="onSuccess" :on-error="onError"> <i slot="default" class="el-icon-plus"></i> <div slot="file" slot-scope="{file}"> <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""> <span class="el-upload-list__item-actions"> <span v-if="true" class="el-upload-list__item-delete" v-on:click="removePic(file)"> <i class="el-icon-delete"></i> </span> </span> </div> </el-upload> </el-col> </el-row> <el-row> <el-col :span="1"> <label>商品说明:</label> </el-col> <el-col :span="23"> @*<el-form-item label="商品说明:" prop="desc"> <textarea rows="10" v-model="form.Desc" style="100%;"></textarea> </el-form-item>*@ <textarea rows="30" style="100%" v-model="form.Desc"></textarea> </el-col> </el-row> <el-row> <el-col :span="4"> <el-form-item label="兑换截至时间:" prop=""> <el-date-picker v-model="form.Deadline" type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss"> </el-date-picker> </el-form-item> </el-col> </el-row> <el-row style="text-align:center;"> <el-button type="primary" v-on:click="SaveGoods('form')">保存提交</el-button> </el-row> </el-form> </div> <script src="~/app-js/tools.js"></script> <script> let isSubmiting = false; let goodsId = "@(ViewBag.goodsId??0)"; let imgUrl = GetIMGUrl(); let imgLength = 0; let checkRequireScore = function (rule, value, callback) { if (!value) { return callback(new Error('所需积分不能为空')); } if (!Number.isInteger(value)) { callback(new Error('请输入数字值')); } else { callback(); } }; let checkPerPersonCount = function (rule, value, callback) { if (!value) { return callback(new Error('每人限额不能为空')); } if (!Number.isInteger(value)) { callback(new Error('请输入数字值')); } else { callback(); } }; let checkStock = function (rule, value, callback) { if (!value) { return callback(new Error('每人限额不能为空')); } if (!Number.isInteger(value)) { callback(new Error('请输入数字值')); } else { callback(); } }; let checkPrice = function (rule, value, callback) { var regPos = /^d+(.d+)?$/; //非负浮点数 //var regNeg = /^(-(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数 if (!regPos.test(value)) { callback(new Error('请输入数字值')); } else { callback(); } }; let fileCount = 0; let vm = new Vue({ el: "#app", data: { form: { Name: '', RequireScore: '', PerPersonCount: '', Stock: '', Desc: '', Price: '', Deadline: '', Imgs: [], removeIdList: [], }, fileList: [], uploadFileList: [], rules: { Name: [ { required: true, message: '请输入物品名称', trigger: 'blur' }, ], RequireScore: [ { validator: checkRequireScore, trigger: 'blur' } ], PerPersonCount: [ { validator: checkPerPersonCount, trigger: 'blur' } ], Stock: [ { validator: checkStock, trigger: 'blur' } ], Price: [ { validator: checkPrice, trigger: 'blur' } ], desc: [ { required: true, message: '请填写商品描述', trigger: 'blur' } ] }, }, beforeCreate() { }, created() { }, beforeMount() { }, mounted() { this.loadGoods(); }, components: { }, methods: { loadGoods() { this.form.removeIdList = []; if (goodsId!="0") { ajax({ url: '/api/score-mgr/Score/GetGoods', params: { goodsId: goodsId } }).then((res) => { let data = res.data; if (data.Result) { this.form = data.Content; imgLength = data.Content.GoodsImgs.length; for (var i = 0; i < data.Content.GoodsImgs.length; i++) { let obj = new Object(); obj.url = imgUrl + data.Content.GoodsImgs[i].ImageUrl; obj.uid = data.Content.GoodsImgs[i].Id; obj.name = data.Content.GoodsImgs[i].Id; this.fileList.push(obj); } this.form.removeIdList = []; fileCount = this.fileList.length; } }).catch((err) => { console.log(err); this.form.removeIdList = []; }); } }, handleRemove(file) { }, removePic(file) { let files = this.$refs.uploadRef.uploadFiles; let index = files.findIndex(fileItem => { return fileItem.uid === file.uid }) this.form.removeIdList.push(files[index].uid); for (var i = 0; i < this.fileList.length; i++) { if (files[index].uid == this.fileList[i].uid) { fileCount = fileCount - 1; } } console.log(this.form.removeIdList); files.splice(index, 1); }, getScoreForm() { return this.form; }, onSuccess(res) { if (res.Result) { this.form.Imgs.push(res.Content); } else { alert("商品信息保存失败,请刷新页面重新上传"); return; } console.log(this.fileList.length); //if (this.form.Imgs.length + this.fileList.length == this.$refs.uploadRef.uploadFiles.length + this.form.removeIdList.length) console.log(this.form.removeIdList.length); console.log(fileCount); if (this.form.Imgs.length + fileCount == this.$refs.uploadRef.uploadFiles.length) { ajax({ url: '/api/score-mgr/Score/SaveGoods', method: "post", data: this.form }).then((res) => { let data = res.data; if (data.Result) { alert("物品配置保存成功"); location.href = "/Score/ScoreExchange"; } }).catch((err) => { console.log(err); alert("保存错误"); return; }); } }, onError(res) { isSubmiting = false; alert("设置失败"); return; }, SaveGoods(formName) { this.$refs[formName].validate((valid) => { if (valid) { if (this.$refs.uploadRef.uploadFiles.length > fileCount) { this.form.Imgs = []; console.log(this.$refs.uploadRef.uploadFiles.length); this.$refs.uploadRef.submit(); return; } ajax({ url: '/api/score-mgr/Score/SaveGoods', method: "post", data: this.form }).then((res) => { let data = res.data; if (data.Result) { alert("物品配置保存成功"); location.href = "/Score/ScoreExchange"; } }).catch((err) => { console.log(err); alert("保存错误"); return; }); } else { alert("请填写正确的内容,然后保存提交!"); return false; } }); }, ReturnGoodsList() { location.href = "/Score/ScoreExchange"; } } }); </script>
因为是后端是mvc模式,前端使用vue模式调用接口模式是使用ajax调用,所以后端控制器中仅是页面,没有接口逻辑,具体的接口代码是使用api格式。
后端上传代码如下:
//mvc controller 代码:
[MvcPermissionAuthorize("6103")]//权限验证
public async Task<IActionResult> AddExchangeSetting()
{
string goodsId = Request.Query["goodsId"];
ViewBag.goodsId = goodsId;
return View();
}
//接口逻辑代码:
/// <summary> /// 上传图片 /// </summary> /// <returns></returns> [HttpPost] [MvcPermissionAuthorize("6103")] public BaseResponseResult<string> GoodsUploadImg() { BaseResponseResult<string> res = new BaseResponseResult<string>(); var file = Request.Form.Files.FirstOrDefault(); if (file == null) throw new DFBusinessException("文件为空"); var ss = Directory.GetCurrentDirectory(); //var ss1 = AppContext.BaseDirectory; //图片上传地址 string imgAddress = ConfigLoader.ScoreCommonSettings.UploadImageAddress; string macPath = ss + "/wwwroot" + imgAddress; if (!System.IO.Directory.Exists(macPath)) { Directory.CreateDirectory(macPath); // 不存在就创建目录 } System.Drawing.Image img = System.Drawing.Bitmap.FromStream(file.OpenReadStream()); string fileName = Snowflake_19_Helper.NewId().ToString() + ".jpg"; string imgPath = macPath + "/" + fileName; var mstream = ImageHelper.GetThumbPicStream(file.OpenReadStream(),800,800, img.RawFormat, ThumbPicModeEnum.hw); Bitmap bt = new Bitmap(mstream); bt.Save(imgPath); bt.Dispose(); img.Dispose(); return res.GetSuccess(imgAddress+"/" + fileName); } /// <summary> /// 新添兑换物品 /// </summary> /// <returns></returns> [HttpPost] [MvcPermissionAuthorize("6103")] public async Task<BaseResponseResult<int>> SaveGoods(SaveGoodsModel goods) { List<GoodsImages> goodsImgs = new List<GoodsImages>(); if (goods.Imgs != null) for (int i = 0; i < goods.Imgs.Count; i++) { GoodsImages imgs = new GoodsImages(); imgs.Id = Snowflake_19_Helper.NewId(); imgs.GoodsId = goods.Id; imgs.ImageUrl = goods.Imgs[i]; imgs.CreateTime = DateTime.Now; goodsImgs.Add(imgs); } goods.CreateTime = DateTime.Now; var lst = await _scoreService.SaveGoods(goods, goodsImgs, goods.removeIdList); return lst; }