常用案例之上传头像

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: ttc
  Date: 2018/7/13
  Time: 9:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
    <script>
        window.onload = function () {
            document.querySelector("#file").onchange = function () {
                var req = new XMLHttpRequest();
                var form = new FormData(document.getElementById("form1"));
//              form.append("file",document.querySelector("#file").files[0]);
                req.open("post", "${pageContext.request.contextPath}/upload.do", true);
                req.send(form);
                req.onload = function () {
                    document.getElementById("img").src = "${pageContext.request.contextPath}/pic/" + req.responseText;
                }
            }
        }
    </script>
    <style>
        img {
            width: 200px;
            height: 200px;
            border-radius: 50%;
        }
    </style>
</head>
<body>
<form id="form1" action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">
    <img id="img" src="${pageContext.request.contextPath}/pic/${pic}"
         onerror="this.src='${pageContext.request.contextPath}/default.jpg'">
    <input type="file" name="file" id="file">
</form>
</body>
</html>

servlet

package com.neu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by ttc on 2018/7/13.
 */
@WebServlet(name = "UploadServlet",urlPatterns = "/upload.do")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("file");
        String name = part.getSubmittedFileName();
        UUID uuid = UUID.randomUUID();

        String path = request.getServletContext().getRealPath("")+"/pic/";
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        part.write(path+uuid+name);
        response.getWriter().print(uuid+name);
        request.getSession().setAttribute("pic",uuid+name);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

目录结构

image.png

注意:在web自动部署时,空文件夹不会被自动创建到部署目录中,所以需要在后台判断文件夹是否存在,如果不存在,就需要创建文件夹。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,970评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,982评论 19 139
  • “尚好的青春都是你” 对于所有与青春有关的剧,都没有抵抗力。朋友说,不看了,每次都是哭鼻子。已经长大了,老是去回忆...
    那自叙阅读 603评论 3 12
  • 薇儿房间的一面墙上整整齐齐地挂着十二排挂钩,每排十二行,一共一百四十四个。 每个挂钩上都卡着一张黑白色照片,下面钩...
    Zeke扑浪阅读 493评论 0 3
  • 原文地址:http://www.myexception.cn/jquery/2062227.html 1. 使用了...
    欧石南阅读 3,150评论 0 2