前言:
在项目最开始的时候,我们默认从牛客网的静态资源库中选择一张照片作为用户的头像,但在实际开发中,我们还要考虑用户可以自己设置头像。

思路:
上传文件(上传到硬盘服务器上 或者 上传到云服务器上,开发过程中将文件传输到自己电脑的,项目上线后将路径改变即可)
● 请求:必须是post请求
● 表单:enctype=“multipart/form-data”
● Spring MVC:通过 MultipartFile 处理上传文件

开发步骤:
● 访问账号设置页面
● 上传头像
● 获取头像

文章目录

  • 1 编写文件存储路径
  • 2 编写 controller 类
  • 3 编写前端代码
  • 4 说明

1 编写文件存储路径

application.properties中编写。

# 项目路径
server.servlet.context-path=/community
# communtiy 域名
community.path.domain=http://localhost:8080
# 文件上传地址
community.path.upload=d:/upload_test/data/upload

2 编写 controller 类

package com.zcq.community.controller;import com.zcq.community.annotation.LoginRequired;
import com.zcq.community.entity.User;
import com.zcq.community.service.UserService;
import com.zcq.community.util.CommunityUtil;
import com.zcq.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.*;@Controller
@RequestMapping("/user")
public class UserController {private static final Logger logger = LoggerFactory.getLogger(UserController.class);@Value("${community.path.upload}")private String uploadPath;@Value("${community.path.domain}")private String domain;@Value("${server.servlet.context-path}")private String contextPath;@Autowiredprivate UserService userService;@Autowiredprivate HostHolder hostHolder;// 访问 /setting 路径@LoginRequired@RequestMapping(path = "/setting", method = RequestMethod.GET)public String getSettingPage() {return "/site/setting";}// 上传用户的头像@LoginRequired@RequestMapping(path = "/upload", method = RequestMethod.POST)public String uploadHeader(MultipartFile headerImage, Model model) {if(headerImage == null) {model.addAttribute("error", "您还没有选择图片");return "/site/setting";}// 读取并暂存文件的后缀String fileName = headerImage.getOriginalFilename();String suffix = fileName.substring(fileName.lastIndexOf("."));if(StringUtils.isBlank(suffix)) {model.addAttribute("error", "文件的格式不正确");return "/site/setting";}// 生成随机文件名fileName = CommunityUtil.generateUUID() + suffix;// 确定文件存放的路径File dest = new File(uploadPath + "/" +fileName);try {// 存储文件headerImage.transferTo(dest);} catch (IOException e) {logger.error("上传文件失败" + e.getMessage());throw new RuntimeException("上传文件失败, 服务器发生异常");}// 更新当前用户的头像的路径(web路径)// http://localhost:8080/community/user/header/xxx.pngUser user = hostHolder.getUser();String headerUrl = domain + contextPath + "/user/header/" +fileName;userService.updateHeader(user.getId(), headerUrl);return "redirect:/index";}// 获取头像, 在浏览器上显示@RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {// 服务器存放的路径fileName = uploadPath + "/" + fileName;// 文件的后缀String suffix = fileName.substring(fileName.lastIndexOf("."));// 响应图片response.setContentType("image/" + suffix);try(// FileInputStream 需要手动关闭,OutputStream response对象会自动关闭FileInputStream fis = new FileInputStream(fileName);OutputStream os = response.getOutputStream();){// 二进制形式保存文件byte[] buffer = new byte[1024];int b = 0;// 等于 -1 就结束while ((b = fis.read(buffer)) != -1) {os.write(buffer, 0, b);}} catch (IOException e) {logger.error("读取头像失败" + e.getMessage());}}}

3 编写前端代码

<form method="post" enctype="multipart/form-data" th:action="@{/user/upload}"><div><label>选择头像:</label><div><div><!-- 注意: name属性与所需要的参数名称保持一致 --><!-- div里的内容默认不显示(靠前端代码实现),只有当th:class不为空时才显示数据 --><input type="file" th:class="|custom-file-input ${error!=null?'is-invalid':''}|"id="head-image" name="headerImage" lang="es" required=""><label>选择一张图片</label><div th:text="${error}">该账号不存在!</div></div></div></div><div>...</div>
</form>

4 说明

头像大小不能过大,否则会导致无法存入!

仿牛客论坛项目之修改用户头像相关推荐

  1. 仿牛客论坛项目(下)

    代码仓库:https://gitee.com/qiuyusy/community 仿牛客论坛项目(上) 仿牛客论坛项目 15.kafka 1.阻塞队列 2.Kafka入门 简介 术语解释 下载 配置 ...

  2. 仿牛客论坛项目(上)

    代码仓库:https://gitee.com/qiuyusy/community 仿牛客论坛项目(下) 仿牛客论坛项目上 1. Spring 在测试类中使用Spring环境 @Primary的作用 @ ...

  3. 仿牛客论坛项目(3)

    仿牛客论坛项目 一.阻塞队列 1.1 测试 二.kafka入门 2.1 kafka下载 2.2 测试 三.Spring整合kafka 3.1 引入依赖 3.2 修改配置文件 3.3 测试 四.发布系统 ...

  4. 仿牛客论坛项目(5)

    仿牛客论坛项目 一.SpringSecurity入门案例 1.1 添加依赖 1.2 配置文件 1.3 工具类 CommunityUtil 1.4 配置类 SecurityConfig 1.5 实体类 ...

  5. 仿牛客论坛项目(4)

    仿牛客论坛项目 一.Elasticsearch入门 1.1 elasticsearch安装 1.2 修改config目录下的elasticsearch.yml配置文件 1.3 配置环境变量 1.4 下 ...

  6. 仿牛客论坛项目全面大总结

    1.核心功能: - 发帖.评论.私信.转发: - 点赞.关注.通知.搜索: - 权限.统计.调度.监控: 2.核心技术: - Spring Boot.SSM - Redis.Kafka.Elastic ...

  7. SpringBoot仿牛客论坛项目实战

    Community 论坛项目 转载请附带原文链接: 1. 环境搭建与技术栈说明 1.0 项目架构图 1.1 技术要求 熟悉快速开发框架:SpringBoot2.3.x 整合 SpringMVC + M ...

  8. (仿牛客论坛项目)01 - 开发社区首页

    文章目录 前言 1.做项目的步骤 2.开发社区首页功能分步 2.1 User 类 2.2 UserMapper 接口 2.3 UserMapper 映射文件 2.4 编写测试类 3.开发社区首页,显示 ...

  9. 仿牛客论坛项目部署总结

最新文章

  1. ## 应用Python爬虫、Flask框架、Echarts、WordCloud等技术实现豆瓣Top250数据分析
  2. 干货篇:AI赋能医药工业发展案例
  3. python朋友圈为什么这么火-看我如何用Python发一个高逼格的朋友圈
  4. win10安装tesserocr配置 Python使用tesserocr识别字母数字验证码
  5. jboss eap_HawtIO在JBoss EAP上(第二部分)
  6. go语言打包html,Go语言-打包静态文件
  7. java map扩容机制_java中ConcurrentHashMap的扩容机制问题
  8. rest接口webservice接口利用http请求方式发送数据
  9. 如何启动mysql集群_如何搭建一个 MySQL 分布式集群
  10. 9月6日 星期二 晴(晚上有雨)
  11. 【Git】git tag
  12. java学习思维导图
  13. Radware荣获ICSA实验室“卓越信息安全测试奖”
  14. MySQL——连接查询
  15. linux fd dup 使用
  16. 手机号码为344格式
  17. 集合添加元素python_Python 集合(set)添加元素-Python 集合(set) add-Python 集合(set) update-嗨客网...
  18. 安装缺少的python包
  19. 过滤器VS拦截器的4个区别,看完豁然开朗!
  20. 2023AIGC产业发展及应用白皮书.pdf(附下载链接)

热门文章

  1. php继承exten,jQuery的extend方法【三种】
  2. C语言开发数字华容道实现,jQuery实现数字华容道小游戏(实例代码)
  3. 山东省计算机网络与信息安全管理,山东省委网信办和国家计算机网络与信息安全管理中心山东分中心签署协议 将在这四方面展开合作...
  4. ruby网站部署到服务器,ruby网站部署到服务器
  5. 洗衣机洗涤部分c语言程序,51单片机洗衣机控制板及C语言程序
  6. element ui富文本编辑器的使用(quill-editor)
  7. php 引入vue-cli,vue-cli如何引入layui
  8. PyQt5学习:Qtdesigner设计转换而来的界面.py文件与 2k等高分辨率屏幕不匹配或自适应问题,导致部分控件显示不完全解决办法
  9. 一名软件测试工程师的一天24小时,主要工作内容详细流程...
  10. 11款很酷的新编程工具