文件上传(图片为例)

commons-fileupload-1.3.3.jarcommons-io-2.6.jar

或者

commons-fileupload-1.2.2.jarcommons-io-2.4.jar

需要先导包!

1、Commons-FileUpload组件

Commons是Apache开放源代码组织的一个Java子项目,其中的FileUpload是用来处理HTTP文件上传的子项目

1、Commons-FileUpload组件特点

  1. 使用简单:可以方便地嵌入到JSP文件中,编写少量代码即可完成文件的上传功能
  2. 能够全程控制上传内容
  3. 能够对上传文件的大小、类型进行控制

2、该组件涉及的API如下:

1、FileItem 接口

2、FileItemFactory 接口与 DiskFileItemFactory 类

3、ServletFileUpload类

3、上传

1、JSP页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>上传示例页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
	<form action="uploadServlet.do" method="post"
		enctype="multipart/form-data">
		<table align="center">
			<tr>
				<td align="right">昵称:</td>
				<td><input type="text" placeholder="输入昵称" name="name" /></td>
			</tr>
			<tr>
				<td align="right">密码:</td>
				<td><input type="password" placeholder="输入密码" name="pad" /></td>
			</tr>
			<tr>
				<td align="right">上传头像:</td>
				<td><input type="file" name="img" /></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit" /></td>
			</tr>
		</table>
	</form>
</body>
</html>

2、Servlet页面(为了展示效果,仅在控制台输出了上传的内容)

package wendi.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import wendi.entity.User;

/**
 * Servlet implementation class uploadServlet
 */
@WebServlet("/uploadServlet.do")
public class uploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		User user = new User();
		// 判断是否是多部件表单
		if (ServletFileUpload.isMultipartContent(request)) {
			// 创建缓存对象
			FileItemFactory dff = new DiskFileItemFactory();
			// 创建上传的核心对象
			ServletFileUpload sfu = new ServletFileUpload(dff);
			try {
				// 解析为list集合
				List<FileItem> fs = sfu.parseRequest(request);

				// 分析每个FileItem对象
				for (FileItem f : fs) {
					if (f.isFormField()) {
						// 是普通表单元素
						// 获得表单元素的name属性值
						String inputName = f.getFieldName();
						// 获得表单元素的value值
						String inputValue = f.getString("utf-8");
						if ("name".equals(inputName)) {
							user.setName(inputValue);
						}
						if ("pad".equals(inputName)) {
							user.setPad(inputValue);
						}
					} else {
						// 是上传框传来的文件
						// 获取上传文件的原名称
						String oldName = f.getName();
						System.out.println("old:" + oldName);
						if (oldName != null && !"".equals(oldName)) {

							// 获得上传文件的后缀名
							String suffix = oldName.substring(oldName.lastIndexOf("."));
							System.out.println(suffix);
							// 判断上传文件是否是图片格式
							if (".jpg".equalsIgnoreCase(suffix) || ".jpeg".equalsIgnoreCase(suffix)
									|| ".png".equalsIgnoreCase(suffix)) {
								String newName = new Date().getTime() + suffix;
                                                                //图片上传的地址
								File newFile = new File("D:/apache-tomcat-8.0.50/webapps/img/" + newName);
								// 把FileItem里面的图片数据以二进制复制到newFile里面去
								try {
									f.write(newFile);
								} catch (Exception e) {
									e.printStackTrace();
								}
								System.out.println("new :" + newName);
								user.setImg(newName);
							}

						}
					}
				}

			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
		System.out.println(user);

	}

}

注意事项:

1、表单需要标明为多部件表单,否则无法实现文件上传;

2、表单提交方式需是post,因为get方式上传大小有限制

<form action="uploadServlet.do" method="post" enctype="multipart/form-data">

<form/>

3、 所需的包在JDK内部有重复包名,不要导错

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

4、上传的详细步骤在上面Servlet页面内有实例

5、将所需的jar包放在WebContent/WEB-INF/lib文件夹下

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值