# 代码案例:

# html

<form action="${pageContext.request.contextPath}/addImgServlet" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="icon">请上传您的头像</label>
        <input type="file" name="icon" multiple="multiple" id="icon">
    </div>
    <button type="submit" class="btn btn-danger">上传头像</button>
</form>

# java

  • domain
@SuppressWarnings("all")
@Getter
@Setter
@ToString
public class Img {
    private Integer id;
    private String imagePath;
    private String oldName;
}
  • JdbcUtils
@SuppressWarnings("all")
public class JdbcUtil {
    private static DataSource source;
    static{
        Properties pro = null;
        try{
            pro = new Properties();
            InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            pro.load(in);
            source = DruidDataSourceFactory.createDataSource(pro);
        }catch(IOException e){
            throw new RuntimeException(e);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws SQLException {
        return source.getConnection();
    }
    public static DataSource getSource(){
        return source;
    }
}
  • Dao
public interface UserMapper {
    int addImg(String addr,String marks);
}
-----------------------------impl-----------------------------
public class UserMapperImpl implements UserMapper {
    private static JdbcTemplate jdbc = new JdbcTemplate(JdbcUtil.getSource());
    public int addImg (String addr,String marks) {
        String sql = "insert into img (image_path,old_name) values (?,?)";
        return jdbc.update(sql,addr,marks);
    }
}
  • Service
public interface UserService {
    int addImg(String adrr,String marks);
}
-----------------------------impl-----------------------------
public class UserServiceImpl implements UserService {
    private UserMapper userMapper = new UserMapperImpl();
    public int addImg (String addr,String marks) {
        return userMapper.addImg(addr,marks);
    }
}
  • servlet
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   String filehead = "E:/Idea.2021.2.2/Demo/maven-Demo-dkx/src/main/resources/userHead.txt";
   User o = (User) request.getSession().getAttribute("user");
   Integer name = o.getUsername();//12341234
   request.setCharacterEncoding("utf-8");
   Part icon = request.getPart("icon");
   String contentType = icon.getContentType();
   String file = "";
   String imgP = "image/";
   String ImgUUID = "";
   // 判断上传文件类型
   if (contentType.startsWith("image/")) {
      String fileName = icon.getSubmittedFileName();
      String extension = fileName.substring(fileName.lastIndexOf("."));
      ImgUUID = UUID.randomUUID().toString() + extension;
      String cPath = "E:/Idea.2021.2.2/Demo/maven-Demo-dkx/src/main/webapp/";
      file = cPath + imgP + ImgUUID;
      System.out.println(file);
      icon.write(file);
   }else{
      request.getSession().setAttribute("error_head","上传的头像格式错误,请注意是否填写了头像备注");
      request.getRequestDispatcher("/headSculpture.jsp").forward(request,response);
      return;
   }
   BufferedReader reader = new BufferedReader(new FileReader(filehead));
   String content = reader.readLine();
   delHead(content);
   FileWriter writer = new FileWriter(filehead);
   writer.write(ImgUUID);
   String strname = name.toString();
   int i = userService.delImg(strname);
   if (i > 0) {
      System.out.println("头像更换成功");
   }else{
      System.out.println("头像更换出现问题");
   }
   writer.close();
   reader.close();
   System.out.println("用户: "+strname+"添加了一个头像");
   int flag = userService.addImg(file,strname);
   if (flag > 0) {
      request.getSession().setAttribute("error_head","头像添上传了");
      request.getRequestDispatcher("/headSculpture.jsp").forward(request,response);
      return;
   }else{
      request.getSession().setAttribute("error_head","头像上传失败了");
      request.getRequestDispatcher("/headSculpture.jsp").forward(request,response);
      return;
   }
}
public static void delHead(String file){
   String filepath = "E:/Idea.2021.2.2/Demo/maven-Demo-dkx/src/main/webapp/image/"+file;
   File f = new File(filepath);
   if (f.isFile()) {
      f.delete();
      System.out.println("之前的头像删除了: "+f.getName()+" 被删除的头像命名");
   }
}

上传完成后的效果,后面就是让页面展示出头像了

image-20230413123611962