file上传文件操作【练习】
程序员文章站
2022-06-03 09:16:50
...
1、项目目录结构如下
2、导入jar包
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
文件上传需要fileupload包,fileupload包需要io包;
不要导apache的包,项目换服务器时会出问题
3、index.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/FileUploadServlet" method="post"enctype="multipart/form-data">
用户:<input type="text" name="username"/></br>
<input type="file" name="photo"/></br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
4、Servlet代码
package com.neuedu.servlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class FileUploadServlet
*/
@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//创建工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
//创建ServletFileUpload对象,通过这个对象完成上传功能!
ServletFileUpload fileUpload=new ServletFileUpload(factory);
//限定文件上传大小
fileUpload.setFileSizeMax(1024*50);
//限定所有文件的总大小,用于多文件上传
fileUpload.setSizeMax(1024*150);
ServletContext servletContext=request.getServletContext();
//获取项目上传路径
String realPath = servletContext.getRealPath("/upload");
System.out.println(realPath);
File file=new File(realPath);
if (!file.exists()){
file.mkdir();
}
//利用fileUpload对象解析request请求
try {
List<FileItem> fileList=fileUpload.parseRequest(request);
for(FileItem item:fileList){
if(item.isFormField()){
//代表普通表单项
String name = item.getFieldName();
String value= item.getString("utf-8");
System.out.println(name+":"+value);
}
else{
//代表上传的文件
long size = item.getSize();
String contentType = item.getContentType();
String name = item.getName();
//浏览器适配,防止文件目录被一同当作文件名
if(name.contains("\\")){
name= name.substring(name.lastIndexOf("\\")+1);
}
//uuid_name.jpg
String prefix=UUID.randomUUID().toString();
prefix = prefix.replace("-", "");
String fileName=prefix+"_"+name;
String fieldName = item.getFieldName();
System.out.println(size+":"+contentType+":"+name+":"+fieldName);
try {
item.write(new File(realPath+"\\"+fileName));
} catch (Exception e) {
// TODO: handle exception
}
}
}
}catch(FileSizeLimitExceededException e){
System.out.println("文件大小不可以超过50k");
}catch(SizeLimitExceededException e){
System.out.println("总大小不可以超过150k");
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
上一篇: Servlet基础