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 {
}
}
目录结构
注意:在web自动部署时,空文件夹不会被自动创建到部署目录中,所以需要在后台判断文件夹是否存在,如果不存在,就需要创建文件夹。