普通Servlet上传,需要两个包:commons-fileipload和commons-ior
Servlet doPost:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//实例化一个文件工厂
FileItemFactory factory = new DiskFileItemFactory();
//配置上传组件ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//从request得到所有上传域的列表
List<FileItem> list = upload.parseRequest(request);
for (FileItem item : list) {
//如果是上传域的文件域
if (!item.isFormField()) {
//上传于的Name
String fileName = item.getName();
//截取扩展名
int idx = fileName.lastIndexOf(".");
String extension = fileName.substring(idx);
//name 文件名
String name = new Date().getTime() + extension;
//得到文件夹的物理路径
String path = this.getServletContext().getRealPath(
"\\upload");
//创建一个File
File file = new File(path + "\\" + name);
try {
//写入文件
item.write(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
Jsp: 注意Form表单里的属性:enctype="multipart/form-data"
<form action="servlet/Upload" name="form1" method="post"
enctype="multipart/form-data">
<table>
<tr>
<td>
上传:
</td>
<td>
<input type="file" name="upload">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="上传">
</td>
</tr>
</table>
</form>