JAVAweb-文件上传
1、创建一个新的项目,导入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2、编写jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<%--
GET:上传文件大小有限制
POST:上传文件大小没有限制
${pageContext.request.contextPath}
--%>
<form action="upload.do" enctype="multipart/form-data" method="post">
上传用户:<input type="text" name="username"><br/>
<P><input type="file" name="file1"></P>
<P><input type="file" name="file1"></P>
<P><input type="submit" value="提交"> | <input type="reset"></P>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%=request.getAttribute("msg")%>
</body>
</html>
3、Servelet类
@WebServlet("/upload.do")
public class FileServlet extends HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(request)) {
return;
}
String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()&& !uploadFile.isDirectory()) {
System.out.println(uploadFile+"不存在,需要创建!");
uploadFile.mkdir();
}
String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
File tempFile = new File(tempPath);
if (!tempFile.exists()) {
tempFile.mkdir();
}
try {
DiskFileItemFactory factory = getDiskFileItemFactory(tempFile);
ServletFileUpload upload = getServletFileUpload(factory);
String msg = uploadParseRequest(upload, request, uploadPath);
System.out.println(msg);
if (msg == "文件上传成功!") {
System.out.println("文件位置在:"+uploadPath);
request.setAttribute("msg", msg);
request.getRequestDispatcher("info.jsp").forward(request, response);
} else {
msg = "请上传文件";
request.setAttribute("msg", msg);
request.getRequestDispatcher("info.jsp").forward(request, response);
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
public static DiskFileItemFactory getDiskFileItemFactory(File file) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024);
factory.setRepository(file);
return factory;
}
public ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener() {
@Override
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("总大小:" + pContentLength + ",已上传:" + pBytesRead);
}
});
upload.setHeaderEncoding("UTF-8");
upload.setFileSizeMax(1024 * 1024 * 10);
return upload;
}
public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath)
throws FileUploadException, IOException {
String msg = "";
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem fileItem : fileItems
) {
if (fileItem.isFormField()) {
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
System.out.println(name + ":" + value);
} else {
String uploadFileName = fileItem.getName();
System.out.println("上传的文件名: " + uploadFileName);
if (uploadFileName.trim().equals("") || uploadFileName == null) {
continue;
}
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
System.out.println("文件信息[文件名: " + fileName + " ---文件类型" + fileExtName + "]");
String uuidPath = UUID.randomUUID().toString();
String realPath = uploadPath + "/" + uuidPath;
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
InputStream in = fileItem.getInputStream();
FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
byte[] buffer = new byte[1024 * 1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
in.close();
msg = "文件上传成功!";
fileItem.delete();
}
}
return msg;
}
}
4、文件上传成功后找不到文件位置解决
idea中javaweb项目文件上传成功,但是却在指定位置找不到文件???
出现这样的问题是tomcat部署的问题
- 以war部署,上传的文件会在Tomcat服务器文件夹下:
- 而以war exploded 部署,项目会在idea工作空间中部署,就可以找到上传的文件了
|