JSP 用Commons-FileUpload组件控制文件上传

示范: 

JSP页面代码:


<防和谐input type="file" name ="file2"/>

<防和谐input type="file" name ="file2"/>

<防和谐input type="submit" value="提交"/>

<防和谐/form>



Servlet页面内Java代码:


String uploadFilePath=request.getSession().getServletContext().getRealPath("/uplod"); //获取JSP页面的form表单是不是为 //enctype="multipart/form-data"

boolean isMultipart =ServletFileUpload.isMultipartContent(request);try {

if(isMultipart){

//创建工厂

FileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload= new ServletFileUpload(factory);

Listitems = upload.parseRequest(request);   

 Iteratoriter = items.iterator();

while(iter.hasNext()){ 

//依次处理每个文件

FileItem item = iter.next();

String fileName= item.getName(); //表单字段的name属性值

if(fileName !=null && fileName!=""){

File src= new File(item.getName());

File save = new File(uploadFilePath, item.getName());

item.write(save);

}

}

}

} catch (FileUploadException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

你可能感兴趣的:(JSP 用Commons-FileUpload组件控制文件上传)