图片上传、预览 存到本地

本文介绍了一个前端实现头像上传与更换的功能案例,详细展示了使用HTML、JavaScript及FormData API进行图片预览与提交的过程,并实现了局部页面更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先来前端页面代码

		<!-- 账号设置  -->
		<div id="center_right_zhsz" hidden="hidden">
			<div style="font-family: MicrosoftYaHei;font-size: 14px;">
				<div style="width: 64px;height: 21px;color: #4d4d4d;font-size: 16px;margin-left: 34px;margin-top: 40px;">基本资料</div>
				<div style="margin-top: 50px;">
					<div style="width: 28px;height: 19px;color: #7f7f7f;margin-left: 282px;float: left;margin-right: 40px;">头像</div>
					<div style="font-size: 12px;color: #c3c3c3;"><img th:src="@{/static/images/icons/icon-ts.png}" style="margin-bottom: -2px;margin-right: 10px;">仅支持GIF/JPG/PNG格式、大小不超过2M</div>
				</div>
				<div style="height: 100px;margin-left:410px;width: 120px; ">
					<img id="zhsztxxgq" th:src="@{/static/images/icons/touxiang.png}" style="width: 96px;height: 96px;border-radius: 50px;margin-top: 30px;z-index: -1;">
					<img id="zhsztxxgz" onclick="sctx()" hidden="hidden" th:src="@{/static/images/icons/sctx.png}" style="width: 96px;height: 96px;border-radius: 50px;cursor:pointer;z-index: 0;margin-top: -100px;margin-bottom: 20px;">
					<input hidden="hidden" id="xtxtp" type="file" accept="image/gif, image/jpg, image/png"/>
					<input id="photoCover" class="form-control" readonly type="text" hidden="hidden">
					<input id="zhszid" hidden="hidden" value="60">
				</div>
				<div style="margin-top: 50px;">
					<div style="margin-left: 282px;margin-right: 100px;float: left;color: #7f7f7f;font-size: 14px;">昵称</div>
					<div id="zhszncdiv" hidden="hidden"><input id="zhsznc2" style="width: 128px;color: #4d4d4d;"/></div>
					<div id="zhsznc" style="color: #4d4d4d;font-size: 14px;">yxzj1991</div>
				</div>
			</div>
			<img id="zhsztxan" onclick="htx()" th:src="@{/static/images/icons/icon-xg.png}" style="position: absolute;top: 540px;left: 940px;cursor: pointer;">
			<img id="zhszncan" onclick="hnc()" th:src="@{/static/images/icons/icon-xg.png}" style="position: absolute;;top: 585px;left: 940px;cursor: pointer;">
			<img id="zhszmman" onclick="hmm()" th:src="@{/static/images/icons/icon-xg.png}" style="position: absolute;;top: 925px;left: 940px;cursor: pointer;">
			<div id="zhsz_tx" hidden="hidden">
				<img  onclick="htxqx()" th:src="@{/static/images/icons/icon-qx.png}" style="position: absolute;;top: 540px;left: 940px;cursor: pointer;">
				<img  onclick="htxqr()" th:src="@{/static/images/icons/icon-bc.png}" style="position: absolute;;top: 540px;left: 912px;cursor: pointer;">
			</div>
			<div id="zhsz_nc" hidden="hidden">
				<img  onclick="hncqx()" th:src="@{/static/images/icons/icon-qx.png}" style="position: absolute;;top: 585px;left: 940px;cursor: pointer;">
				<img  onclick="hncqr()" th:src="@{/static/images/icons/icon-bc.png}" style="position: absolute;;top: 585px;left: 912px;cursor: pointer;">
			</div>
			<div id="zhsz_mm" hidden="hidden">
				<img  onclick="hmmqx()" th:src="@{/static/images/icons/icon-qx.png}" style="position: absolute;;top: 925px;left: 940px;cursor: pointer;">
				<img  onclick="hmmqr()" th:src="@{/static/images/icons/icon-bc.png}" style="position: absolute;;top: 925px;left: 912px;cursor: pointer;">
			</div>
			<div>
				<div style="width: 64px;height: 21px;color: #4d4d4d;font-size: 16px;margin-left: 34px;margin-top: 98px;">账号安全</div>
				<div style="margin-top: 50px;">
					<div style="margin-left: 282px;margin-right: 72px;color: #7f7f7f;float: left;font-size: 14px;">仓库名称</div>
					<div id="zhszmysmc" style="color: #4d4d4d;font-size: 14px;">石家庄海森化工有限公司</div>
				</div>
				<div style="margin-top: 30px;">
					<div style="margin-left: 282px;margin-right: 72px;color: #7f7f7f;float: left;font-size: 14px;">身份权限</div>
					<div style="color: #4d4d4d;font-size: 14px;">操作员</div>
				</div>
				<div style="margin-top: 30px;">
					<div style="margin-left: 282px;margin-right: 72px;color: #7f7f7f;float: left;font-size: 14px;">登录账号</div>
					<div id="zhszzh" style="color: #4d4d4d;font-size: 14px;">1321321322</div>
				</div>
				<div style="margin-top: 30px;">
					<div style="margin-left: 282px;margin-right: 72px;color: #7f7f7f;float: left;font-size: 14px;">登录密码</div>
					<div id="zhszmm2" style="color: #4d4d4d;font-size: 14px;">••••••••</div>
					<input id="zhszmm" hidden="hidden" value="zhang012345"/>
				</div>
				<div id="zhszmmxgdiv" hidden="hidden">
					<div style="margin-top: 30px;">
					<div style="margin-left: 282px;margin-right: 72px;color: #7f7f7f;float: left;font-size: 14px;">新的密码</div>
					<div style="color: #4d4d4d;font-size: 14px;"><input id="zhszxmm" style="width: 128px;"/></div>
					<div style="margin-top: 30px;">
					<div style="margin-left: 282px;margin-right: 72px;color: #7f7f7f;float: left;font-size: 14px;">确认密码</div>
					<div style="color: #4d4d4d;font-size: 14px;"><input id="zhszxmm2" style="width: 128px;"/></div>
					<span id="mmbyz" hidden="hidden" style="color: #fe4a48;font-size: 12px;margin-left:412px;">两次密码填写不一致</span>
					<span id="mmxt" hidden="hidden" style="color: #fe4a48;font-size: 12px;margin-left:412px;">与旧密码相同,请更改</span>
				</div>
				</div>
				
				</div>
			</div>
			<div style="margin-top: 50px;">
				<button onclick="zhsztc()" style="width: 128px;height: 40px;background-color: #74bdff;border-radius: 5px;color: #ffffff;font-size: 16px;border: none;margin-left: 393px;">退出登录</button>
			</div>
		</div>

这是样子

下面的是图片点击事件(点击图片触发 那个隐藏的input的点击事件)

/* 上传头像 */
function sctx(){
	$("#xtxtp").click();
}
 $(function(){
     $("#xtxtp").change(function(e){
         var file = e.target.files[0]||e.dataTransfer.files[0];
         //在此限制图片的大小
         var imgSize = file.size;
         console.log(imgSize);
         //35160  计算机存储数据最为常用的单位是字节(B)
         //在此处我们限制图片大小为2M
         if(imgSize>2*1024*1024){
        	 alert('上传的图片的大于2M,请重新选择');
        	 $(this).val('')
        	 return false;
         }
         $('#photoCover').val(document.getElementById("xtxtp").files[0].name);
         if(file){
             var reader = new FileReader();
             reader.onload=function(){
                 $("#zhsztxxgz").attr("src", this.result);
                // $("#zhsztxxgq").hide();
             }

             reader.readAsDataURL(file);
         }
     });
 })
到这里只是替换页面上的图片,相当于预览功能。还没投提交到后台

/* 换头像确认 */
function htxqr(){
	if($("#zhsztxxgz")[0].src.split("/")[6]=="sctx.png"){
		$("#zhsztxan").show();
		$("#zhsztxxgq").show();
		$("#zhsztxxgz").hide();
		$("#zhsz_tx").hide();
	}else{
		$("#zhsztxan").show();
		$("#zhsztxxgq").show();
		$("#zhsztxxgz").hide();
		$("#zhsz_tx").hide();
		$("#zhsztxxgq").attr("src",$("#zhsztxxgz")[0].src);
		$("#zhsztxxgz").attr("src","/static/images/icons/sctx.png");
		
		var file = document.getElementById("xtxtp").files[0];
		var form = new FormData();
		form.append("file", file);
		
		var xhr = null; //得到xhr对象
        if(XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open("post", "warehouseauditor/htx", true);//设置提交方式,url,异步提交
        xhr.onload = function ()
        {
            var data = xhr.responseText;    //得到返回值
        }
        xhr.send(form);
	}
}
可以看到用了 formData,以前提交图片都是form表单直接提交,不能局部刷新页面,用formData 你可以局部刷新,form表单度都可以不写(貌似是html5才有的)
form.append("file", file);相当于key  value  你有多个参数是也可以一起加的

下面是controller层

	/**
	 * 换头像
	 * @param file
	 * @param id
	 * @param request
	 * @param response
	 */
	@RequestMapping("htx")
	public void htx(@RequestParam("file")MultipartFile file,HttpServletRequest request,HttpServletResponse response){
		 try {
			 PortalUser user =(PortalUser) request.getSession().getAttribute("user");
			 if(user!=null){
				 PortalUser entity = portalUserService.getEntity(user.getId());
				 String fileName=file.getOriginalFilename();
				 //获取扩展
				 String extName = fileName.substring(fileName.lastIndexOf("."));//.jpg
				 String nname = fileName.substring(0,fileName.lastIndexOf("."));//w文件名
				 //UUID
				 String uuid = UUID.randomUUID().toString().replace("-", "");
				 //新名称
				 String newName = nname+"-"+uuid+extName;
				 //获取输出流
				 OutputStream os=new FileOutputStream("D:/photo2/"+newName);
				 //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
				 InputStream is=file.getInputStream();
				 int temp;
				 //一个一个字节的读取并写入
				 while((temp=is.read())!=(-1))
				 {
					 os.write(temp);
				 }
				 os.flush();
				 os.close();
				 is.close();
				 entity.setPhotoUrl("D:/photo2/"+newName);
				 portalUserService.save(entity);
				 RenderUtil.renderSuccess("修改成功", response);
			 }
	        } catch (IOException e) {
	        	e.printStackTrace();
	        }  
        
	}

加了个uuid防止重名  不过我是先建好这个photo2这个文件夹的,不然你要加个判断



### 使用 Vue3 和 Element Plus 实现图片上传并保存至本地 为了实现在 Vue3 项目中使用 Element Plus 组件库来完成图片上传功能,并将这些图片保存到本地文件系统,需遵循特定的方法。此过程涉及配置 `el-upload` 组件以阻止其默认行为即自动上传文件,改为通过自定义逻辑触发上传操作,在客户端先预览再决定是否真正发送给服务器或仅存于浏览器环境内模拟存储效果。 #### 配置 el-upload 组件防止自动上传 首先应调整 `<el-upload>` 的属性设置,关闭自动上传选项并通过编程方式控制何时发起请求: ```html <template> <div id="app"> <!-- 设置 :auto-upload 属性为 false 来禁用自动上传 --> <el-upload class="upload-demo" drag action="" multiple :limit="10" :on-change="handleChange" :before-remove="handleBeforeRemove" :file-list="fileList" :auto-upload="false"> <i class="el-icon-upload"></i> <div class="el-upload__text">拖拽图片至此处, 或者点击选择</div> <div class="el-upload__tip" slot="tip">支持多张图片批量导入。</div> </el-upload> <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传至服务器</el-button> <el-button style="margin-left: 10px;" size="small" type="primary" @click="saveToLocal">保存到本地</el-button> </div> </template> ``` 上述模板展示了如何构建一个简单的文件上传界面[^3]。 #### JavaScript 方法实现 接下来编写相应的事件处理器方法用于管理文件列表以及执行实际的上传动作或者模拟保存到本地的行为: ```javascript <script setup lang="ts"> import { ref } from 'vue'; // 声明响应式的 fileList 数组用来存放已选中的文件对象 const fileList = ref([]); function handleChange(file, fileList) { console.log('File selected:', file); } async function handleBeforeRemove(file, fileList) { return new Promise((resolve, reject) => { this.$confirm(`确定要移除 ${file.name} 吗?`) .then(() => resolve(true)) .catch(() => reject(false)); }); } function submitUpload() { // 这里应该放置向远程API提交POST请求的具体代码... alert("This would send files to a server."); } function saveToLocal() { const blobArray = fileList.value.map(item => item.raw); // 获取原始文件数组 for (let i = 0; i < blobArray.length; ++i){ let urlCreator = window.URL || window.webkitURL; let imageUrl = urlCreator.createObjectURL(blobArray[i]); var link=document.createElement('a'); link.href=imageUrl; link.download=blobArray[i].name; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(imageUrl); } } </script> ``` 这段脚本实现了两个主要功能:一是允许用户交互式地添加/删除待上传项;二是提供了两种不同的处理路径——既可以尝试真正的网络传输也可以直接下载链接让用户的计算机保存副本作为临时解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值