文件上传
Posted 美味的你
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件上传相关的知识,希望对你有一定的参考价值。
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界面:
以上是关于文件上传的主要内容,如果未能解决你的问题,请参考以下文章
ajaxFileUpload上传带参数文件及JS验证文件大小