Jsp+Servlet文件上传功能实现

本文介绍使用MyEclipse 6.5进行文件上传的全过程,包括创建项目、实现Servlet处理上传请求、配置web.xml及搭建前端页面等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工具: myeclipse 6.5

1.
新建项目 fileUpload

com.shiryu 包下新建 Servlet FileUpload.java

package com.shiryu;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUpload extends HttpServlet {

    private static final long serialVersionUID = -5361390019270693076L;
   
    //
文件上传路径
    private String uploadPath;

    //
临时文件路径
    private File tempPath;

    public FileUpload() {
        uploadPath = "D://test//";
        tempPath = new File("C://windows//temp//");
    }

    public void init() throws ServletException {

        if (!(new File(uploadPath)).isDirectory())

            (new File(uploadPath)).mkdir();

        if (!tempPath.isDirectory())

            tempPath.mkdir();
    }

    public void destroy() {
        super.destroy();
    }

    @SuppressWarnings({ "unchecked", "unchecked" })
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
       
        res.setContentType("text/html; charset=GB2312");
       
        PrintWriter out = res.getWriter();
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
       
        factory.setSizeThreshold(4096);
       
        factory.setRepository(tempPath);
       
        ServletFileUpload upload = new ServletFileUpload(factory);
       
        upload.setSizeMax(0xf4240L);
       
        List fileItems = null;
       
        try {
            fileItems = upload.parseRequest(req);
            Iterator iter = fileItems.iterator();
            String regExp = ".+(.+)$";
            
            //
限制上传文件的格式
            String errorType[] = { ".exe", ".com", ".cgi", ".asp" };
            Pattern p = Pattern.compile(regExp);

            while (iter.hasNext()) {

                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {

                    String name = item.getName();
                   
                    long size = item.getSize();
                   
                    if (name != null && !name.equals("") || size != 0L) {
                       
                        Matcher m = p.matcher(name);
                       
                        boolean result = m.find();
                       
                        if (result) {

                            for (int temp = 0; temp < errorType.length; temp++)
                               
                                if (m.group(1).endsWith(errorType[temp]))

                                    throw new IOException(name + ": wrong type");

                            try {
                                item.write(new File(uploadPath, m.group(1)));

                            } catch (Exception e) {
                                out.println(e);
                            }
                        } else {
                            throw new IOException("fail to upload");
                        }
                    }
                }
            }
        } catch (IOException e) {

            out.println("222" + e);

        } catch (FileUploadException e1) {

            e1.printStackTrace();
        }
    }
}


2.
配置 web.xml 文件的内容

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>


    <servlet>
        <servlet-name>upload_3</servlet-name>
        <servlet-class>com.shiryu.FileUpload</servlet-class>
        <init-param>
            <param-name>upload</param-name>
            <param-value>/WEB-INF/upload</param-value>
        </init-param>
    </servlet>


    <servlet-mapping>
        <servlet-name>upload_3</servlet-name>
        <url-pattern>/upload_3</url-pattern>
    </servlet-mapping>

</web-app>


3.
前台 upload_3.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>index.html</title>
    </head>

    <body>
        <form action="upload_3" method="post" enctype="multipart/form-data" name="form1">
            <input type="file" name="file">
            <input type="submit" name="Submit" value="upload">
        </form>

        <form name="uploadform" method="POST" action="upload_3" ENCTYPE="multipart/form-data">

            <table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF">

                <tr>
                    <td width="100%" colspan="2">
                    file1:<input name="x" size="40" type="file">
                    </td>
                </tr>

                <tr>
                    <td width="100%" colspan="2">
                        file2:<input name="y" size="40" type="file">
                    </td>
                </tr>

                <tr>
                    <td width="100%" colspan="2">
                        file3:<input name="z" size="40" type="file">
                    </td>
                </tr>

            </table>

            <br />
            <table>
                <tr>
                    <td align="center">
                        <input name="upload" type="submit" value="sure" />
                    </td>
                </tr>
            </table>

        </form>

    </body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值