使用common-fileupload实现文件上传功能

首先需要下载并导入common-fileupload和common-io连个jar包,然后将要提交的表单method设置为post,并且添加enctype属性,属性值为:multipart/form-data

其中上传图片的标签为<input type="file" name="picpath">

下面看具体的代码:

<%@ page language="java" contentType="text/html; charset=utf-8" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
    <form action="doAdd.jsp" method="post" enctype="multipart/form-data">
    	<table>
    		<tr>
    			<td>用户姓名:</td>
    			<td><input type="text" name="username"/></td>
    		</tr>
    		<tr>
    			<td>密码:</td>
    			<td><input type="text" name= "password"/></td>
    		</tr>
    	</table>
    	<input type="file" name="picPath"/> 
    	<input type="submit" value="提交" /> 
    </form>
  </body>
</html>

然后看处理的JSP页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.io.*,java.util.*,org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>   
    <title>My JSP 'doAdd.jsp' starting page</title>
  </head>
  
  <body>
     <%
    	//String uploadFilePath = request.getSession().getServletContext().getRealPath("/upload/" );
     	//检查请求类型
     	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
     	//当enctype="multipart/form-data"并且method是post时,isMultipart为真
     	if(isMultipart){
     		FileItemFactory factory = new DiskFileItemFactory();
     		ServletFileUpload upload = new ServletFileUpload(factory);
     		//转换请求对象
     		List<FileItem> items = null;
     		items=upload.parseRequest(request);
     		Iterator<FileItem> iterator = items.iterator();
     		while(iterator.hasNext()){
     			FileItem item = iterator.next();
     			//保存上传文件
     			if(item.isFormField()){
     				//处理普通文本字段
     				String fieldName = item.getFieldName();
     				if(fieldName.equals("username")){
     					out.print(item.getString());
     				}else if(fieldName.equals("password")){
     					out.print(item.getString());
     				}
     			}else{
     				File fullfile = new File(item.getFieldName());
     				File uploadfile = new File("f:/image/",item.getFieldName());
     				item.write(uploadfile);
     			}
     		}
     	}
      %>
  </body>
</html>


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值