现在的位置: 首页 > 综合 > 正文

文件上传——servlet实现

2012年10月21日 ⁄ 综合 ⁄ 共 4379字 ⁄ 字号 评论关闭

1M=1024*1024个字节——>约等于1000000了,所以1M大约是1000000字节
10M=1024*1024*10 个字节

注意:
上传时需要设置html表单:method="post",
enctype="multipart/form-data"    ,此时就不能在java中通过request.getParameter()来获取数据了
图片上传存储的问题:
1、文件名称与物料名称相同,将文件存储到磁盘
2、将文件名称存储到数据表中,将文件存储到磁盘
3、将文件内容全部存储到数据库表中

示例:图片到存到服务器磁盘上,图片名保存到数据库

第一步:servlet中
public class FileUploadServlet extends HttpServlet {
        
    private File uploadPath;
    private File tempPath;
    
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // form提交采用multipart/form-data,无法采用req.getParameter()取得数据
        // DiskFileItemFactory对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置文件缓存大小
        factory.setSizeThreshold(4096);
        // 当文件超出缓存大小时会被保存在临时目录里
        factory.setRepository(tempPath);
        // ServletFileUpload对象
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 文件的最大值
        upload.setSizeMax(1000000 * 20);
        try {
            List fileItems = upload.parseRequest(req);                //ServletFileUpload对象解析request得到上传的文件列表
            String itemNo = "";
            for (Iterator iter = fileItems.iterator(); iter.hasNext();) {
                FileItem item = (FileItem) iter.next();
                
                //是普通的表单输入域
                if(item.isFormField()) {
                    if ("itemNo".equals(item.getFieldName())) {        //item.getFieldName()取得form表单里名字是itemNo的控件
                        itemNo = item.getString();                                    //取得itemNo的控件对应的文本值
                    }                                                                                            //itemNo是物料id,因为要上传的图片名与对应的物料保存到表中,所以此处才取此值
                }
                //不是普通的form表单输入域,此处指的是上传控件
                if (!item.isFormField()) {
                    String fileName = item.getName();                            //jsp中对应的上传图片名字,此处不能通过request取值
                    long size = item.getSize();
                    if ((fileName == null || fileName.equals("")) && size == 0) {
                        continue;
                    }
                    //截取字符串 如:C:\WINDOWS\Debug\PASSWD.LOG
                    fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
                    item.write(new File(uploadPath, fileName));            //在制定的上传目录里创建指定名字的图片
                    itemManager.uploadItemImage(itemNo, fileName);    //将图片名称上传到数据库,已在别处实现
                }
            }
            res.sendRedirect(req.getContextPath() + "/servlet/item/SearchItemServlet");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApplicationException("上传失败!");
        }
    }

    public void init() throws ServletException {
        uploadPath = new File(getServletContext().getRealPath("upload"));    //在application下根据虚拟目录得到绝对路径,此处的虚拟是WebRoot/upload
        System.out.println("uploadPath=====" + uploadPath);
        //如果目录不存在
        if (!uploadPath.exists()) {
            //创建目录
            uploadPath.mkdir();                                                //创建上传目录
        }
        
        //临时目录
        tempPath = new File(getServletContext().getRealPath("temp"));
        if (!tempPath.exists()) {
            tempPath.mkdir();                                                    //创建临时目录
        }
        //显示调用父类的init方法
        super.init();
    }
}

第二步:jsp中:
<form name="itemForm" target="_self" id="itemForm" method="post" action="servlet/item/FileUploadServlet" enctype="multipart/form-data">
    ``<input type="hidden" name="itemNo" value="<%=item.getItemNo() %>">
        <hr width="97%" align="center" size=0>
        <tr>
            <td height="29">
                <div align="right">
                    物料代码:&nbsp;
                </div>
            </td>
            <td>
                <%=item.getItemNo() %>
            </td>
        </tr>
        <tr>
            <td height="74">
                <div align="right">
                    图片:&nbsp;
                </div>
            </td>
            <td>
                <img src="upload/<%=item.getFileName() %>" width="85" height="49">
            </td>
        </tr>
        <tr>
            <td width="22%" height="29">
                <div align="right">
                    <font color="#FF0000">*</font>选择图片:&nbsp;
                </div>
            </td>
            <td width="78%">
                <input name="fileName" type="file" class="text1" size="40" maxlength="40">
            </td>
        </tr>
        <hr width="97%" align="center" size=0>
        <div align="center">
            <input name="btn_upload" class="button1" type="submit" id="btn_upload" value="上传">
        </div>
</form>

抱歉!评论已关闭.