Servlet上传文件详细解析以及注意事项
来源:互联网 发布:解压缩软件 安卓 编辑:程序博客网 时间:2024/04/30 18:07
准备阶段,下载需要的包:
在Servlet中进行文件上传需要用到外部的类库,apache提供了这些类库, 主要需要commons-fileupload.jar和commons-io.jar
下载的步骤如下:
进入www.apache.org网站, ——>在Projects下找到commons,点击进入——>找到Components下的FileUpload,点击进入就可以找到下载
页面如下:
可以看到这里有开发指南和下载地址,如果要详细学习,慢慢看这里的资源就可以了。
commons-io.jar包的下载地址:http://commons.apache.org/fileupload/dependencies.html
把两个jar包放到WEB-INF的lib目录下。
开发阶段:
上传页面:index.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head>10 <base href="<%=basePath%>">11 12 <title>文件上传</title>13 <meta http-equiv="pragma" content="no-cache">14 <meta http-equiv="cache-control" content="no-cache">15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">17 <meta http-equiv="description" content="This is my page">18 <!--19 <link rel="stylesheet" type="text/css" href="styles.css">20 -->21 </head>22 23 <body>24 <form action="upload" method="post" enctype="multipart/form-data">25 文件别名:<input type="text" name="filename"><br>26 选择文件:<input type="file" name="fileupload"><br>27 <input type="submit" value="提交">28 29 </form>30 </body>31 </html>
这里注意第24行,上传文件时要指定提交方法method="post", 信息类型为enctype="multipart/form-data"
上传功能servlet:FileUpload
1 package com.sunflower.servlet; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.Iterator; 6 import java.util.List; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet;10 import javax.servlet.http.HttpServletRequest;11 import javax.servlet.http.HttpServletResponse;12 13 import org.apache.commons.fileupload.FileItem;14 import org.apache.commons.fileupload.FileItemFactory;15 import org.apache.commons.fileupload.FileUploadException;16 import org.apache.commons.fileupload.disk.DiskFileItemFactory;17 import org.apache.commons.fileupload.servlet.ServletFileUpload;18 19 public class FileUpload extends HttpServlet {20 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {21 req.setCharacterEncoding("UTF-8");22 fileControl(req, resp);23 }24 25 /**26 * 上传文件的处理27 */28 private void fileControl(HttpServletRequest req, HttpServletResponse resp) throws ServletException {29 30 // 在解析请求之前先判断请求类型是否为文件上传类型31 boolean isMultipart = ServletFileUpload.isMultipartContent(req);32 33 // 文件上传处理工厂34 FileItemFactory factory = new DiskFileItemFactory();35 36 // 创建文件上传处理器37 ServletFileUpload upload = new ServletFileUpload(factory);38 39 // 开始解析请求信息40 List items = null;41 try {42 items = upload.parseRequest(req);43 }44 catch (FileUploadException e) {45 e.printStackTrace();46 }47 48 // 对所有请求信息进行判断49 Iterator iter = items.iterator();50 while (iter.hasNext()) {51 FileItem item = (FileItem) iter.next();52 // 信息为普通的格式53 if (item.isFormField()) {54 String fieldName = item.getFieldName();55 String value = item.getString();56 req.setAttribute(fieldName, value);57 }58 // 信息为文件格式59 else {60 String fileName = item.getName();61 int index = fileName.lastIndexOf("\\");62 fileName = fileName.substring(index + 1);63 req.setAttribute("realFileName", fileName);64 65 // 将文件写入66 // String path = req.getContextPath();67 // String directory = "uploadFile";68 // String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/" + directory;69 String basePath = req.getRealPath("/uploadFile");70 File file = new File(basePath, fileName);71 try {72 item.write(file);73 }74 catch (Exception e) {75 e.printStackTrace();76 }77 }78 }79 80 try {81 req.getRequestDispatcher("/uploadsuccess.jsp").forward(req, resp);82 }83 catch (IOException e) {84 e.printStackTrace();85 }86 }87 }
这里要注意第66~68行,将文件上传到Web项目的"uploadFile"文件夹中,如果用这种方法得到的路径是"http://localhost:8080/upload/uploadFile", 而创建File类用的路径是绝对路径,这样就会出问题,所以这里要用的是得到真实路径的方法HttpServletRequest.getRealPath().
以上是最简单的文件上传,如果要加入上传的限制可以在DiskFileItemFactory和ServletFileUpload中进行限制:
在34行后加入:
//创建临时文件目录 File tempFile = new File(req.getRealPath("/temp")); //设置缓存大小 ((DiskFileItemFactory) factory).setSizeThreshold(1024*1024); //设置临时文件存放地点 ((DiskFileItemFactory) factory).setRepository(tempFile);
注意第72行的FileItem.write()方法,如果使用了这个方法写入文件,那么临时文件会被系统自动删除.
在38行后加入:
//将页面请求传递信息最大值设置为50M upload.setSizeMax(1024*1024*50); //将单个上传文件信息最大值设置为6M upload.setFileSizeMax(1024*1024*6);
原文:http://www.cnblogs.com/hanyuan/archive/2012/06/09/upload.html
- Servlet上传文件详细解析以及注意事项
- Servlet上传文件详细解析以及注意事项
- Servlet上传文件详细解析以及注意事项
- Servlet上传文件详细解析以及注意事项
- Servlet上传文件详细解析以及注意事项
- Jsp Servlet +SmartUpload 实现文件上传.以及上传乱码问题解决.
- 【JavaWeb-13】文件上传DiskFileItemFactory、ServletFileUpload以及注意事项、文件下载及注意事项
- Asynctask解析以及注意事项
- Asynctask解析以及注意事项
- Asynctask解析以及注意事项
- Asynctask解析以及注意事项
- Asynctask解析以及注意事项
- ajax实现文件上传以及后台servlet中的处理总结
- Servlet 文件上传 : 解析request的InputStream流
- Servlet如何编写以及写Servlet注意事项
- PHP 上传文件注意事项
- java上传文件注意事项
- PHP上传文件注意事项
- PHP获取客户端数据保存到MySQL数据库 出现中文乱码解决方案
- 资源resource
- 导入ctl文件
- 自动升级程序
- Maven使用常见问题
- Servlet上传文件详细解析以及注意事项
- Firefox下载含空格的文件
- 同步、异步、互斥、信号量、阻塞、非阻塞
- oracle 数据快修复—之使用RMAN 块介质恢复
- maven 自动部署到 tomcat7
- MAVEN pom.xml 解读
- Boost日期处理
- 数据结构——排序(二)
- iOS中 判断字符串 中文字符 字母 数字 以及下划线