common-fileupload:可以实现文件的上传和批量上传 ,同时也可以实现表单中其他元素的上传
common-io:对io的操作
服务器端的代码如下:
public class ImageUploadServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isFileUpload = ServletFileUpload.isMultipartContent(request);//检测是否存在文件上传的请求
if(isFileUpload){
// 处理磁盘文件工厂类
FileItemFactory factory = new DiskFileItemFactory();
// 文件上传的处理类
ServletFileUpload upload = new ServletFileUpload(factory);
//解析上传的文件
try {
List fileItems = upload.parseRequest(request);
for (Iterator iterator = fileItems.iterator(); iterator
.hasNext();) {
FileItem fileItem= (FileItem) iterator.next();
//判断上传的表单域是否为文件上传,false 表示文件上传<input type="file" />
//true 表示为非文件上传
if(fileItem.isFormField()){
//对非文件上传的处理
if("userName".equals(fileItem.getFieldName())){
}
}else {
String contentType = fileItem.getContentType()
.toLowerCase();// 比如:image/pjpg
//进行格式的判断
if (contentType.indexOf("jpg") != -1
|| contentType.indexOf("jpeg") != -1
|| contentType.indexOf("png") != -1
|| contentType.indexOf("gif") != -1 || contentType.indexOf("bmp") !=-1) {
//对文件上传的处理
String fileUploadPath=fileItem.getName();
// 上传之后文件的名字要唯一:采用当前上传的系统时间的毫秒数作为文件的名字
String time = System.currentTimeMillis() + "";// 当前系统时间
String postfix = fileUploadPath.substring(fileUploadPath.lastIndexOf("."));//获取文件的后缀名
String fileName = time+postfix;
String contextPath =this.getServletContext().getRealPath("imageTemp");//获取工程中的名为imageTemp的目录
String filePath = contextPath+File.separator+fileName;
File file = new File(filePath);//代表上传文件的目录
FileOutputStream out = new FileOutputStream(file);
InputStream in = fileItem.getInputStream();
IOUtils.copy(in,out);
IOUtils.closeQuietly(out);//关闭输出流
IOUtils.closeQuietly(in);//关闭输出流
}else {
System.out.println("文件格式错误");
}
}
}
} catch (FileUploadException e) {
System.out.println("文件上传异常");
}
}
}
}