Servlet 实现文件上传需要 commons-fileupload-1.2.2.jar
,解析上传的二进制数据。
表单需要修改enctype属性值为 multipart/form-data,提交方法为post 。上传文件要使用文件域(<input type="file" >
)。
<form action="..." method="post" enctype="multipart/form-data">
<input type="file">
<input type="submit value="上传文件">
</form>
Servlet 类的doPost() 方法:
response.setCharacterEncoding("UTF-8");
File file = null;
String description1 = null, description2 = null;
DiskFileUpload diskFileUpload = new DiskFileUpload();
try {
// 解析请求中的文本域和上传的文件,并装入 list
List<FileItem> list = diskFileUpload.parseRequest(request);
for(FileItem item:list) {
// 判断是否为文件
if(!item.isFormField()) {
// 获取上传的文件名,创建一个新文件
File remoteFile = new File(new String(item.getName().getBytes(),"UTF-8"));
//System.out.println(remoteFile.getName());
//System.out.println(remoteFile.getAbsolutePath());
// 上传的文件不为空
if(!remoteFile.getName().equals("")) {
// 创建一个和上传文件名称一样的文件
//System.out.println(this.getServletContext().getRealPath("upload")); //上傳的路徑
file = new File(this.getServletContext().getRealPath("upload"),remoteFile.getName());
//System.out.println(file.getParentFile().getName());
file.getParentFile().mkdirs(); // 创建文件夹路径
file.createNewFile(); // 创建新文件
// 将二进制数据输出到文件中
InputStream ins = item.getInputStream(); // 上传的二进制数据
OutputStream ous = new FileOutputStream(file); // 写入创建的文件
try {
byte[] bytes = new byte[1024];
int n ;
while((n = ins.read(bytes)) != -1) {
ous.write(bytes, 0, n);
}
}finally {
ins.close();
ous.close();
}
}
}
}
}catch(FileUploadException e) {
e.printStackTrace();
}
response.getWriter().write("ok");