文件上传,总结步骤:
<1>添加jar包,
commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar
<2>写页面,写出一个form 提交
<3>写一个servlet实现文件上传程序的编写
源码:
表单页:
<form name="f1" id="f1" action="<%=path%>/servlet/UploadServlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Title:</td>
<td><input type="text" name="title" ></td>
</tr>
<tr>
<td>File:</td>
<td><input type="file" name="f" ></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="login"></td>
</tr>
</table>
</form>
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileItemFactory factory=new DiskFileItemFactory(); //针对磁盘文件创建工厂
ServletFileUpload upload=new ServletFileUpload(factory);//通过factory创建一个ServletFileUpload
upload.setHeaderEncoding("UTF-8");//设成你的编码格式
try {
List items=upload.parseRequest(request); //解析请求,获得表单上的一些选项。
Iterator iter=items.iterator();
while(iter.hasNext()){
FileItem item=(FileItem)iter.next(); //取出封装成文件选项
if(!item.isFormField()){ //判断一个参数域是普通的表单输入域,还是文件上传域
String fullFileName=item.getName(); //得到要上传的文件的绝对路径
System.out.println(fullFileName);
int idx=fullFileName.lastIndexOf(".");//找到.的索引号
String subfix=fullFileName.substring(idx);//截取文件全路径
String fileName=new Date().getTime()+subfix;
String path="C:/upload/";//构建上传路径
File f=new File(path+"/");
if (!f.exists()) {
f.mkdirs();
}
try {
item.write(new File(path+"/"+fileName)); //写入文件路径
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}