坐等毕业-整理毕设-上传头像到系统

思路:前台选择文件,发送请求给后台,使用Spring自带MultipartFile类实现文件上传到指定目录,并将文件路径+文件名存储到数据库,页面使用时用Controller返回的数据渲染。

原来的思路:直接存储图片到数据库,结果,吃力不讨好。

环境:SpringBoot Thymeleaf BootStrap

实现:

html页面

			<div class="modal-body">
				<input type="file" id="file" name="file"></input>
			</div>

js点击事件

点击某按钮发送请求上传文件

function subIcon(){
		var formData = new FormData();  
		formData.append('file',$("#file")[0].files[0]);
		debugger;
		$.ajax({
			type: "POST",
	        enctype: 'multipart/form-data',
			url : "/gradesign/family/editIcon",
			data : formData,
			processData: false,  
            contentType: false ,
			success : function(data){
				$("#uploadModal").modal('hide');
				swal({
					title:"家庭头像修改成功!各处图标待网站刷新后刷新。",
					showConfirmButton: false 
				})
				window.setTimeout("window.location.href='/gradesign/familyInfo'",1500);
			},
			error : function(){
				swal("系统错误请联系管理员!");
			}
		})
	};

后台请求处理

         /**
	 * 上传文件:
	 * 1、保存文件至项目/Tomcat路径下
	 * 2、文件路径保存到数据库中
	 */
	@ResponseBody
	@RequestMapping("/editIcon")
	public String familyEditIcon(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
	    JSONObject result = new JSONObject();
	    if (file.isEmpty()) {
		result.put("result", "文件为空");
		return result.toJSONString();
	    }
	    String fileName = file.getOriginalFilename();
	    log.info("上传文件名为:"+fileName);
	    String path = "";
	    File folderFile = new File(".\\src\\main\\resources\\static\\familyicon");
	    String iconPath = null;
	    try {
		iconPath = folderFile.getCanonicalPath();
	    } catch (IOException e1) {
		e1.printStackTrace();
	    }
	    String randomPath = UUID.randomUUID().toString();
	    String filePath = iconPath+"\\"+randomPath+fileName;
	    File dest = new File(filePath);
	    log.info("上传路径为:"+path);
	    if (!dest.getParentFile().exists()) {
		dest.getParentFile().mkdirs();
	    }
	    try {
		file.transferTo(dest);
		result.put("result", "文件上传成功");
		//将路径保存到数据库
		Map<String, String> map = new HashMap<String, String>();
		map.put("iconurl", "/gradesign/familyicon/"+randomPath+fileName);
		map.put("familyaccount",PrincipalFormat.currentFA());
		familyService.familyEditIcon(map);
		return result.toJSONString();
	    } catch (IllegalStateException e) {
		e.printStackTrace();
	    }catch (IOException e) {
		e.printStackTrace();
	    }
	    
	    result.put("result", "文件上传失败");
	    return result.toJSONString();
	}

路径可以写绝对路径也可以用以上相对路径,但是有一个问题就是,在开发中,每次修改头像后都需刷新项目内地址文件夹,然后刷新页面才可以更新图片。

头像页面渲染

返回头像显示页面controller

    @RequestMapping("/familyInfo")
    public String familyInfo(Model model) {
    	Map<String, String> map = new HashMap<String, String>();
    	map.put("familyAccount",PrincipalFormat.currentFA());
    	Family family = familyService.getFamilyByAccount(PrincipalFormat.currentFA());
    	if (family.getIconurl()=="" || family.getIconurl() == null) {
			family.setIconurl("/gradesign/familyicon/2e3f5ccd-9c26-4be2-9bd7-5178041a369ewelcome_back.jpg");
		}
    	model.addAttribute("family", family);
	return "familyInfo";
    }

family.getIconurl()方法获取头像路径,然后返回给页面渲染,即

${family.iconurl},如下:

<img id="icon" th:src="${family.iconurl}" width="170px" height="170px" οnclick="iconEdit()"></img>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值