- 浏览器端的要求
- 表单的提交方法必须是post
- 必须有一个文件上传组件 <input type="file" name="f"/>
- 必须设置表单的enctype="multipart/form-data
<form action="/upload/upload3" enctype="multipart/form-data"
method="post">
用户名:<input type="text" name="username"><br>
文件:<input
type="file" name="f">
<input type="submit"><br>
</form>
- 服务器端的要求
- 在Servelt上添加注解
@MultipartConfig
@WebServlet("/upload3")
@MultipartConfig
public class upload3 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
文件上传如何获取数据
获取普通上传组件
request.getParameter(name属性的值);
获取文件上传组件
Part part = request.getPart("表单文件组件的name名");
//获取文件真实文件名
String header = part.getHeader("content-disposition");
String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
//获取文件的大小
long size = part.getSize();
//把文件写到指定路径
part.write("d:/"+realName);
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<style>
#head{
width: 60px;
height: 60px;
border-radius: 50%;
}
.pic {
position: relative;
display: inline-block;
}
.pic .upload{
position: absolute;
opacity: 0;
width: 80px;
}
</style>
<script>
function doupload() {
alert('ok');
var formobj = document.getElementById('upload');
var form = new FormData(formobj);
var request = new XMLHttpRequest();
request.open("post","${pageContext.request.contextPath}/upload.action",true);
request.send(form);
request.onload = function () {
document.getElementById('head').src = '${pageContext.request.contextPath}/upload/' + request.responseText;
}
}
</script>
</head>
<body>
<form enctype="multipart/form-data" id="upload">
<img src="#" id="head">
<a href="javascript:;" class="pic">
<input type="file" name="upload" onchange="doupload();" class="upload">
UPLOAD555
</a>
</form>
</body>
</html>
@WebServlet(name = "UploadServlet",urlPatterns = "/upload.action")
@MultipartConfig
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Part part = request.getPart("upload");
String filename = part.getSubmittedFileName();
UUID uuid = UUID.randomUUID();
String strPath = request.getServletContext().getRealPath("") + "upload" + File.separator;
File file = new File(strPath);
if (!file.exists()){
file.mkdirs();
}
part.write(strPath + uuid + filename);
request.getSession().setAttribute("picpath",uuid+filename);
response.setContentType("text/html;charset:utf-8");
response.getWriter().println(uuid + filename);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
文件上传可能会遇到的问题
名字重复的问题 如果用户提交了两个1.png只会保存第一次 这样在实际开发中是很不可取的 解决方法uuid
编写上传页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
name:<input type="text" name="user">
选择文件:<input type="file" name="pic">
<input type="submit" value="提交">
</form>
</body>
</html>
开发处理文件上传的Servlet
1、使用注解@MultipartConfig将一个Servlet标识为支持文件上传。
2、Servlet3.0将multipart/form-data的POST请求封装成Part,通过Part对上传的文件进行操作。
3.使用getSubmittedFileName方法需要tomcat8支持。
UploadServlet 代码如下:
@WebServlet(name = "UploadServlet",urlPatterns = "/upload.do")
@MultipartConfig
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String strUser = request.getParameter("user");
System.out.println(strUser);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
Part part = request.getPart("pic");
out.print("文件类型为:" + part.getContentType() + "<br/>");
out.print("文件的大小为:" + part.getSize() + "<br/>");
out.print("文件信息为:" + part.getHeader("content-disposition") + "<br/>");
out.print("文件的名字为:" + part.getSubmittedFileName());
//得到服务器项目发布运行所在地址
String strFolder = request.getServletContext().getRealPath("/image")+ File.separator;
File folder = new File(strFolder);
if(!folder.exists())
{
folder.mkdir();
}
// 此处未使用UUID来生成唯一标识,用日期做为标识
String strNewFilePath = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ part.getSubmittedFileName();
String strFinalPath = strFolder + strNewFilePath;
//查看文件上传路径,方便查找
System.out.println(strFinalPath);
part.write(strFinalPath);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
ajax上传
<%--
Created by IntelliJ IDEA.
User: ttc
Date: 2018/7/13
Time: 8:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script>
function upload() {
var form = new FormData(document.getElementById("upload"));
var req = new XMLHttpRequest();
req.open("post", "${pageContext.request.contextPath}/upload.do", true);
req.send(form);
req.onload = function () {
// alert(req.responseText);
document.getElementById('head').src = '${pageContext.request.contextPath}/upload/'+ req.responseText;
}
}
</script>
</head>
<body>
<form id="upload" action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">
<img src="${pageContext.request.contextPath}/upload/${picpath}" id="head">
<input type="text" name="username" value="zhangsan">
<input type="file" name="file1" onchange="upload();">
<input type="submit">
</form>
</body>
</html>