Servlet代码中
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html:charset=UTF-8");
//初见文件接收的工厂类
DiskFileItemFactory factory=new DiskFileItemFactory();
//创建文件解析对象
ServletFileUpload upload=new ServletFileUpload(factory);
try {
//解析request获得表单的同一文件项(包含普通文件域)
List<FileItem> list=upload.parseRequest(request);
//遍历每一个文本项
for(FileItem i : list ){
//获得原始文件名
String origname=i.getName();
// ----处理上传文件名重名问题----
//a1. 先得到唯一标记
String id = UUID.randomU
UID().toString();
//a2. 拼接文件名
origname = id + File.separatorChar + FilenameUtils.getName(origname);
//获得文本域的名字
String fieldname=i.getFieldName();
//获得普通文本,如果true是普通字段,如果false是文本字段
boolean isfieldform=i.isFormField();
if(!isfieldform){
if(fieldname !=null && !"".equals(fieldname)){
//指定要上传的目录
//String uplcadpath = request.getSession().getServletContext().getRealPath("/upload");
String uplcadpath = getServletContext().getRealPath("/upload");
//创建文件对象
File file = new File(uplcadpath, fieldname);
//文件写入硬盘
i.write(file);
//结果
response.getWriter().print("上传成功");
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
jsp代码
<form action="/shangchuan/shangchuanServlet" method="post" enctype="multipart/form-data">
用户<input name="name" type="text"><br>
用户<input name="password" type="password"><br>
照片<input name="pid" type="file"/><br>
<input type="submit"/ value="tijiao">
</form>
upload文件夹在跟WEB-INT同一级