前端上传图片并修改名字(数据库的图片名字,并非原图片名字)

tech2023-07-18  95

用了两天的时间 百度+大佬的帮助 +我的午睡终于出来了 上最后的图(他叫罗小黑)

html 注意在head上边引入

<th:block th:include="include :: jasny-bootstrap-css"/> <div class="col-sm-8"> <span class="btn btn-white btn-file"><span class="fileinput-new">选择图片</span><input class="form-control" type="file" accept="image/gif,image/png,image/jpeg,image/jpg" id="file_input"></span> <div style="color: red">点击图片则会取消上传</div> </div> <div style="margin-left: 200px"> <div class="pics" id="pics"></div> </div>

js

var pics = []; window.onload = function () { var input = document.getElementById("file_input"); var result, fd, dataArr = []; if (typeof FileReader === 'undefined') { alert("抱歉,你的浏览器不支持 FileReader"); input.setAttribute('disabled', 'disabled'); } else { input.addEventListener('change', readFile, false); } function readFile() { fd = new FormData(); var iLen = this.files.length; for (var i = 0; i < iLen; i++) { let obj=""; if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)) {  //判断上传文件格式 return alert("上传的图片格式不正确,请重新选择"); } var aaa = this.files[i]; var reader = new FileReader(); fd.append(i, this.files[i]); reader.readAsDataURL(this.files[i]); //转成base64 reader.fileName = this.files[i].name; reader.onload = function (e) { var imgMsg = { name: this.fileName,//获取文件名 base64: this.result //reader.readAsDataURL方法执行完后,base64数据储存在reader.result里 } var pic = { alt: this.alt, url: this.url, name:this.name } var formData = new FormData(); formData.append("file", aaa); $.ajax({ url: "/exam/question/questionImgUpload", type: "post", data: formData, async: false, processData: false,//用于对data参数进行序列化处理 这里必须false contentType: false, //必须*/ success: function (data) { obj = data.url; pic.url = obj; } }); pic.alt = aaa; dataArr.push(imgMsg); console.log(obj) result = '<div class="result" id="result" style="width: 100px;margin-top: 10px"><img class="subPic" src="' + this.result + '" alt="' + this.fileName + '"/><label>图片名称</label>' + '<input name="fileName" data-fileUrl="'+obj+'" value="'+this.fileName+'"/></div>'; var div = document.createElement('div'); div.innerHTML = result; div['className'] = 'float'; document.getElementsByClassName('pics')[0].appendChild(div);   //插入dom树 var img = div.getElementsByTagName('img')[0]; img.onload = function () { var nowHeight = ReSizePic(this); //设置图片大小 this.parentNode.style.display = 'block'; var oParent = this.parentNode; if (nowHeight) { oParent.style.paddingTop = (oParent.offsetHeight - nowHeight) / 2 + 'px'; } } // var input = div.getElementsByTagName('input')[i]; // console.log(input) // input.oninput=function(){ // console.log($('input[name="fileName"]').val()); // // console.log(div.getElementsByTagName('input')[0]) // console.log(input) // } pics.push(pic); img.onclick = function () { pics.forEach((item, j) => { if (item.alt == aaa) { pics.splice(j, 1); // 从下标 i 开始, 删除 1 个元素 } }) div.remove();// 在页面中删除该图片元素 } } // var urls; // pics.forEach((item, j) => { // urls=urls+";"+item.url // }) $("#file_input").val("") } } } function ReSizePic(ThisPic) { var RePicWidth = 200; //这里修改为您想显示的宽度值 var TrueWidth = ThisPic.width; //图片实际宽度 var TrueHeight = ThisPic.height; //图片实际高度 if (TrueWidth > TrueHeight) { //宽大于高 var reWidth = RePicWidth; ThisPic.width = reWidth; //垂直居中 var nowHeight = TrueHeight * (reWidth / TrueWidth); return nowHeight; //将图片修改后的高度返回,供垂直居中用 } else { //宽小于高 var reHeight = RePicWidth; ThisPic.height = reHeight; } }

(这个是在网上扒的,因为清了缓存找不到原地址了 ) controller

@PostMapping("/questionImgUpload") @ResponseBody public R pictureUpload(MultipartFile file){ String fileName = file.getOriginalFilename(); fileName = FileUtil.renameToUUID(fileName); Date date = new Date(); FileDO sysFile = new FileDO(FileType.fileType(fileName), "/file/examQusetionImg/"+new SimpleDateFormat("yyyy/MM/dd/").format(date) + fileName, new Date()); try { FileUtil.uploadFile(file.getBytes(), templateConfig.getProfile()+"/examQusetionImg/"+new SimpleDateFormat("yyyy/MM/dd/").format(date), fileName); } catch (Exception e) { return R.error(); } return R.ok().put("url", sysFile.getUrl()); }

(那个r是返会成功失败的)贴上来吧 毕竟我比较笨可能以后就不会了哈哈

@data public class R extends HashMap<String, Object> { private static final long serialVersionUID = 1L; public R() { put("code", 0); put("msg", "success"); } @Override public R put(String key, Object value) { super.put(key, value); return this; } }

还有啊我们用的thymeleaf 所以是他自己封装的 下边是如何把名字传到数据库

//html 在form下写 <input type="hidden" name="fileList" value=""> //提交 function submitHandler() { var list = []; $("input[name='fileName']").each(function (i, ele) { list.push({imgUrl: $(ele).attr("data-fileUrl"), imgName:$(ele).val()}); }) console.log(list) $('input[name="fileList"]').val(JSON.stringify(list)); if ($.validate.form()) { $.operate.save(prefix + "/add", $('#form-question-add').serialize()); } }

然后这样传回去 的是一个String 要转一下 在接收的实体类里写的

private String fileList; public List<ExamQuestionImg> examQuestionImgs() { if (StringUtils.isEmpty(this.fileList)) { return new ArrayList<>(); } return JSON.parseArray(this.fileList, ExamQuestionImg.class); }

加油

最新回复(0)