1.导入两个jar包
FileUpload下载地址:
http://commons.apache.org/fileupload/
下载:commons-fileupload-1.2.2-bin.zip 得到:commons-fileupload-1.2.2.jar
下载:commons-io-1.4-bin.zip 得到:commons-io-1.4.jar
2.表单的属性设置和使用File控件选择文件
<form enctype="multipart/form-data" action="test.jsp" method="post"> 姓名:<input type="text" name="username"> 选择图片:<input type="file" name="myfile"> <input type="submit" value="提交"> </form>
from标签上的method的属性必须取值为post,不能取值get
文件上传页面,代码所示:
<%@page import="java.io.File"%> <%@page import="org.apache.commons.fileupload.FileItem"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %> <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %> <% request.setCharacterEncoding("utf-8"); boolean flag=ServletFileUpload.isMultipartContent(request); if(flag){ DiskFileItemFactory factory=new DiskFileItemFactory(); ServletFileUpload upload=new ServletFileUpload(factory); List<FileItem> fileList= upload.parseRequest(request); Iterator<FileItem> myitor= fileList.iterator(); while(myitor.hasNext()){ FileItem item=myitor.next(); if(item!=null){ if(item.isFormField()){ String name=item.getFieldName(); if(name.equals("username")){ out.print(item.getString("utf-8")); } }else{ String fileName= item.getName(); String path="/WEB-INF/upload/"; String abosolutePath= this.getServletContext().getRealPath(path); File file=new File(fileName); File uploadFile=new File(abosolutePath,file.getName()); item.write(uploadFile); out.print("上传成功"); } } } } %>
web界面: