您的位置:首页 > Web前端 > JavaScript

jsp+servlet文件上传[转+修改]

2013-12-02 09:14 309 查看
源码为网上转载,用于个人学习,我只是在文章中总结了一个上传文件工程的步骤以及方法.

---恢复内容开始---

1:新建一个web工程

2:在WEB-INF/lib中导入两个commons-fileupload-1.2jar和commons-io-1.2.jar

3:在web.xml中配置一个名为UploadServlet的servlet,为其配置映射,并且为servlet配置初始化参数filepath,temppath,temppath表示上传文件比较小时(小于我们设定的值)存放的文件夹位置。而filepath表示上传文件较大时(大于我们设定的值)存放的文件夹位置.

具体代码如下

<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
<init-param>
<param-name>filepath</param-name>
<param-value>try1</param-value>
</init-param>
<init-param>
<param-name>temppath</param-name>
<param-value>try2</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>

4:html页面写form表单

<form method="POST" action="upload" enctype="MULTIPART/FORM-DATA" > <!--"MULTIPART/FORM-DATA"就是一种用表单提交数据的格式-->

<input type="file" name="file" size="30"/>

<input type="submit" value="上传"/>

</form>

5:UploadServlet.java:

首先在UploadServlet定义两个String的变量,分别是temPath以及filePath,其代表的意义在上面以及陈述.

然后在UploadServlet的初始化函数初始化tempPath以及filePath,初始化函数init可以右键点击source选择Override/Implement选择init函数

这里要涉及到获取相对路径和绝对路径的方法

ServletContext = getServletContext();

context.getRealPath("/")表示获得的绝对路径后面再加"/"

context.getContextPath("/")表示获得的相对路径再加“/”

init初始化方法的具体代码如下:

public void init(ServletConfig config) throws ServletException
{
super.init(config);
// 从配置文件中获得初始化参数
filePath = config.getInitParameter("filepath"); //从web.xml中的读取此要初始化的参数
tempPath = config.getInitParameter("temppath");    //同上

ServletContext context = getServletContext();

filePath = context.getRealPath(filePath);         //获取此工程的绝对路径 E:\tomcat\webapps\File\try1
tempPath = context.getRealPath(tempPath);       //获取此工程的绝对路径    E:\tomcat\webapps\File\try2

                                //其实你可以在web.xml中将初始化参数的值设定成你要保存路径的绝对路径,就可以省略这里获取绝对路径                                //的步骤了

  接下来我们再看看doPost方法:

  // doPost
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/plain;charset=gbk");
PrintWriter pw = res.getWriter();
try{
DiskFileItemFactory diskFactory = new DiskFileItemFactory();     
// threshold 极限、临界值,即硬盘缓存 1M
diskFactory.setSizeThreshold(1024 * 1024);
// repository 贮藏室,即临时文件目录
diskFactory.setRepository(new File(tempPath));

ServletFileUpload upload = new ServletFileUpload(diskFactory);
// 设置允许上传的最大文件大小 4M
upload.setSizeMax(4 * 1024 * 1024);
// 解析HTTP请求消息头
List fileItems = upload.parseRequest(req);
Iterator iter = fileItems.iterator();
while(iter.hasNext())
{
FileItem item = (FileItem)iter.next();
if(item.isFormField()) //判断是不是表单输入域,若不是则为文件上传域.
{
System.out.println("处理表单内容 ...");
processFormField(item, pw);
}else{
System.out.println("处理上传的文件 ...");
processUploadFile(item, pw);
}
}// end while()

pw.close();
}catch(Exception e){
System.out.println("使用 fileupload 包时发生异常 ...");
e.printStackTrace();
}// end try ... catch ...
}// end doPost()

}

processFormField(item, pw)处理表单的方法:

private void processFormField(FileItem item, PrintWriter pw)
throws Exception
{
String name = item.getFieldName();
String value = item.getString();
pw.println(name + " : " + value + "\r\n");
}

processUploadFile(item, pw)处理上传文件的方法:

private void processUploadFile(FileItem item, PrintWriter pw)
throws Exception
{
// 此时的文件名包含了完整的路径,得注意加工一下
String filename = item.getName();
pw.println(filename+" 实验");
System.out.println("完整的文件名:" + filename);
int index = filename.lastIndexOf("\\");
filename = filename.substring(index + 1, filename.length());

long fileSize = item.getSize();

if("".equals(filename) && fileSize == 0)
{
System.out.println("文件名为空 ...");
return;
}

File uploadFile = new File(filePath + "/" + filename);
item.write(uploadFile);
pw.println(filename + " 文件保存完毕 ...");
pw.println("文件大小为 :" + fileSize + "\r\n");
}

第一篇博客文,相信也是一个新的开始.

---恢复内容结束---
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: