前端上传图片的原理是:运用<input type=“file” />的标签获取图片信息(file),传给后台,完成上传。
需要页面展示图片的话,可以从接口返回图片地址,放在<img />中
<input type="file" onChange={() => { this.handleUpload(ev.target) }} />
<input type=“file” />的样式不好设置,很难满足样式需求,网上提供几种解决办法,比较好的是设置样式 opcity = 0,使其定位覆盖在按钮之上。
我在开发中觉得依旧不是很好,于是就有了下面的代码:
uploadClick = async () => { const newFile = document.createElement("input"); newFile.setAttribute("type", "file"); newFile.addEventListener("change", () => { this.handleUpload(newFile) }); await newFile.click(); await newFile.remove(); } handleUpload = (newFile) => { const file = newFile.files[0]; // 图片的信息(图片的名称,等) fetch("http://xxxx.xxx", { // 发起请求 method: "post", body: { "multipartFile": file }, Headers: { "userToken": "xxxxxx", // 与后端商量好的请求头 "......": "......" } }).then(res => { if (res.status !== 200) { console.log("上传失败", res) } else { onsole.log("上传成功", res) // 接口返回图片地址,把地址给到 <img src={res.url} /> 进行展示 } }) }
从上面的代码,我们能拿到图片的链接地址,和名称,渲染到页面上就完成了一次上传图片,并且显示
参考文档:雪旭:https://www.cnblogs.com/zimengxiyu/p/11359053.html
原文:https://www.cnblogs.com/MrZhujl/p/12726955.html