背景:表单提交,将用户的头像传递到后台,后台通过流处理,将文件写到文件服务器(本地模拟)并存入数据库
效果图:

前端:
html中需要引入
- jquery-3.4.1.min.js
- jquery.form.js
相应的js代码:
var username=window.localStorage.getItem('username'); $('#username').val(username); //document.cookie获取到所有的cookie $('#cookies').val(document.cookie); //上传头像 $('#dataForm').ajaxForm(function (data) { if (data.code === 2000) { window.location.reload() } else { alert(data.message) } })
后端:
@Value("${filePath}") //具体值在配置文件application.yml中 private String filePath; / * 头像上传 * @param username 指定用户 * @param file 传入的文件 * @param cookie * @return * @throws IOException */ public ResultVO uploadFile(String username, MultipartFile file, String cookie) throws IOException { //获取到文件名称 String fileName = file.getOriginalFilename(); //获取到文件全路径 String path=filePath+ File.separator+fileName; //1.将文件通过IO写到filePath(用本机模拟文件服务器),注意FileOutputStream()中必须得是具体文件 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path)); try { bos.write(file.getBytes()); bos.flush(); } catch (IOException e) { e.printStackTrace(); throw new IOException(ApiResponseCodeEnum.NO_USER.getMessage()); }finally { bos.close(); } //2.存入数据库中 User user=userMapper.getByUsername(username); if (user == null){ return ResultVO.fail(ApiResponseCodeEnum.NO_USER.getCode(), ApiResponseCodeEnum.NO_USER.getMessage()); } user.setImageUrl("../static/img/" +fileName); if (cookie == null){ new File(path).delete(); return ResultVO.fail(); }else { String[] cookiesArr = cookie.split(";"); //我在cookie中存的是{name:token+UUID,value:UUID} for (String temp : cookiesArr) { if (temp.contains("token")) { String[] split = temp.split("=");//前端传来的是"tokenUUID=UUID"字符串 redisUtil.set(split[1], user);//redis存的是{key:UUID,value:user} return ResultVO.success(); } } } //更新数据库 int i = userMapper.updateByPrimaryKeySelective(user); if (i == 0){ //删除文件 new File(path).delete(); return ResultVO.fail(ApiResponseCodeEnum.FAIL_UPLOAD.getCode(), ApiResponseCodeEnum.FAIL_UPLOAD.getMessage()); } return ResultVO.success(); }
其中,filePah是在yml中进行的配置,这里存在了项目的img中
filePath: F:\workspace_webstorm\shop_web\static\img
结尾:我写的不清楚的地方我们可以交流,希望对你有所帮助,也期望指出问题。共同进步~
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/206095.html原文链接:https://javaforall.net
