用servlet和JSP实现文件上传功能

jsp基础见:
http://blog.csdn.net/earbao/article/details/36417165

首先,下载commons-io.jar和commons-fileupload.jar文件,放置于web-inf下的lib目录内。
然后,编写Servlet,核心代码如下:

public void processRequest(HttpServletRequest request, HttpServletResponse response) {
        try{
            request.setCharacterEncoding("gbk");
            response.setContentType("text/html;charset=gbk");

            String upflod = "E:\\web\\file";
            //upload 用来指定被上传过来的文件的存放目录
            String tempflod = "E:\\web\\file\\temp";
            //tempload 用来指定被上传过来的文件的临时目录
            FileItemFactory factory = new DiskFileItemFactory(1000,new File(tempflod));  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            upload.setFileSizeMax(10*1024*1024);
            //最大上传10M文件
            List<FileItem> list = upload.parseRequest(request);
            for(FileItem item :list){
                String fileName = item.getName();
                fileName = fileName.substring(fileName.lastIndexOf("\\")+1,fileName.length());
                File file = new File(upflod+"\\"+fileName);
                System.out.println(fileName);
                item.write(file);
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }


  • FileItemFactory factory = new DiskFileItemFactory(1024,new File(tempflod));

当上传的文件项目比较小时,直接保存在内存中(速度比较快),比较大时,以临时文件的形式,保存在磁盘临时文件夹(虽然速度慢些,但是内存资源是有限的)。
1)第一个参数, public static final int DEFAULT_SIZE_THRESHOLD :将文件保存在内存还是磁盘临时文件夹的默认临界值,值为10240,即10kb,可以自己指定。
2) 第二个参数,private File repository:用于配置在创建文件项目时,当文件项目大于临界值时使用的临时文件夹,默认采用系统默认的临时文件路径,可以通过系统属性 java.io.tmpdir获取。如下代码:
System.getProperty("java.io.tmpdir");
jsp文件如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="upload" method="post" accept-charset="gbk" enctype="multipart/form-data">
    <table>
        <tr>
            <td>个人文件:</td>
            <td><input type="file" name="filename"/></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="文件上传"/>
        </tr>
    </table>
</form>
</body>
</html>

提交方式必须是post。
enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。
默认地,表单数据会编码为 application/x-www-form-urlencoded。就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 “+” 加号,特殊符号转换为 ASCII HEX 值)。
multipart/form-data不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值