网页上传文件,到服务器,再讲数据导入数据库

网页上传时的web.xml文件配置

<servlet>
    <servlet-name>FileUpload</servlet-name>
    <servlet-class>gov.wzzj.servlet.FileUpload</servlet-class>
    <init-param>
      <param-name>upload_path</param-name>
      <param-value>D:\wzgzpt\web\</param-value>
    </init-param>
    <init-param>
      <param-name>upload_tmppath</param-name>
      <param-value>D:</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileUpload</servlet-name>
    <url-pattern>/FileUpload</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>FileUploadServlet</servlet-name>
    <servlet-class>gov.wzzj.servlet.FileUploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileUploadServlet</servlet-name>
    <url-pattern>/FileUploadServlet</url-pattern>
  </servlet-mapping>

struts.xml文件配置

 <constant name="struts.action.excludePattern" value="/DisplayChart/*,/FileUpload/*"/>

jsp页面的form表单
<form action="${ctx}/tzsb/importXls" method="get" id="importjlglForm" name="importjlglForm">
        <table>
            <tr>
                <td align="right" width="30%">选择要导入的文件:</td>
                <td align="left" width="70%">
                <input type="text" id="fj" name="fj"/>&nbsp;&nbsp;  
                <input type="button"  value="选择文件" id="xzwj" onclick="upfilefunc()"/>
                <input type="button"  value="导入Excel" id="ImportXls"/> 
                <input type="hidden" id="filepath" name="filepath"/>
                <input type="hidden" id="dwmc" name="dwmc" value="<c:out value='${paraMap.ssdw}'/>"/>
                <input type="button" id="downLoadModuel" value="下载模板"/>
                </td>
            </tr>
            <tr>
                <td align="right" width="30%" rowspan="6">说明:</td>
                <td align="left" width="25%">
                    <p>1、文件必须是xls格式(microsoft office 97-2003的Excel文件)。请下载标准模板填充数据并导入。</p>
                </td>
            </tr>
            <tr>
                <td align="left" width="25%">
                    <p>2、文件内容格式必须是约定好格式。</p>
                </td>
            </tr>
            <tr>
                <td align="left" width="25%">
                    <p>3、文件内容有一条不合法,将会导入失败。</p>
                </td>
            </tr>
            <tr>
                <td align="left" width="25%">
                    <p>4、气瓶档案信息必须在Excel文件的第一个表(sheet)中。</p>
                </td>
            </tr>
            <tr>
                <td align="left" width="25%">
                    <p>5、一次性导入数据量不能大于500条,文件不能大于1MB。</p>
                </td>
            </tr>
            <tr>
                <td align="left" width="25%">
                    <p>6、日期型数据为空时自动转为"1900-1-1",数字类型数据为空时自动转为'0'。</p>
                </td>
            </tr>

            <tr>
                <td colspan="6" style="text-align: center;; height: 30px; line-height: 30px;">
                    <input type="button" class="foot_btn" onclick="accountUpdate()" value="保存"/>
                    <input type="button" id="reback" name="reback" class="foot_btn" value="返回" onclick="back()"/>
                </td>
            </tr>
        </table>
    </form> 
点击选择文件,调用upfilefunc()方法。
function upfilefunc(){ var str=”${ctx}/upfiles/toupload_apparatus.jsp”; if(navigator.userAgent.indexOf(“Chrome”) >0 ){ var winOption = “height=”+150+”,width=”+450+”,top=50,left=50,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,fullscreen=0”; w=window.open(str,window,winOption); if (str) { window.w.focus();//判断窗口是否打开,如果打开,窗口前置 wTimer=window.setInterval(“wisclosed()”,500); } }else{ w=window.showModalDialog(str,window,”dialogHeight:170px;dialogWidth:450px;status:no;scroll:no;help:no’”); } if(w==undefined) w=”“; document.getElementById(“fj”).value=w; } function wisclosed(){ if(w.closed){ //alert(w.returnValue);//子窗体返回值 document.getElementById(“fj”).value=w.returnValue; //这里可以做赋值操作 window.clearInterval(wTimer) } }
打开窗口,这个窗口让用户选择要上传的文件。
必要前提,`str="${ctx}/upfiles/toupload_apparatus.jsp";这个地址有jsp,`
这个jsp文件。
upload_apparatus。jsp
根据web.xml配置文件,FileUpload是位置是。。
该java类

package gov.wzzj.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import gov.wzzj.pubfunc.publicFunc;

public class FileUpload extends HttpServlet {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private String uploadPath = ""; // 用于存放上传文件的目录
private String uploadtmpPath = ""; // 用于存放上传文件的目录
private File tempPath = null; // 用于存放临时文件的目录
private String filenameType="0";
private String newFilename="";

/**
 * Constructor of the object.
 */
public FileUpload() {
    super();
}

/**
 * Destruction of the servlet. <br>
 */
public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
}

/**
 * The doGet method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to get.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    out.println("<HTML>");
    out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
    out.println("  <BODY>");
    out.print("    This is ");
    out.print(this.getClass());
    out.println(", using the GET method");
    out.println("  </BODY>");
    out.println("</HTML>");
    out.flush();
    out.close();
}

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path=null;
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    //允许设置内存中存储数据的门限,单位:字节
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    //如果文件大小大于SizeThreshold,则保存到临时目录
    factory.setRepository(new File(this.uploadtmpPath));

    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown
    //最大上传文件,单位:字节
    upload.setSizeMax(62914560);
    try {
        List fileItems = upload.parseRequest(request);
        Iterator iter = fileItems.iterator();
        while (iter.hasNext()){
            FileItem item = (FileItem) iter.next();
            if(item.getFieldName().equals("path"))
            {
                path=item.getString();
                break;
            }
        }
        if(path==null||path.equals("")||path.equals("null"))
            path="UpFiles\\";
        else
            path+="\\";
        // 正则匹配,过滤路径取文件名
        String regExp =  "(.+)$";
        // 过滤掉的文件类型
        String[] errorType = { ".exe", ".com", ".cgi", ".asp" };
        Pattern p = Pattern.compile(regExp);
        String itemNo = "";//文件存放路径
        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 == 0)
                    continue;
                Matcher m = p.matcher(name);
                boolean result = m.find();
                if (result) {
                    filenameType="1";
                    newFilename=publicFunc.getTimeStamp()+'.'+publicFunc.getFileType(name);
                    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(this.uploadPath +path+newFilename));
                        out.print("<script>parent.window.returnValue ='"+newFilename+"';window.close();</script>");
                    } catch (Exception e) {
                        System.out.println(e);
                    }

                } else {
                    try {
                        filenameType="0";
                        // 保存上传的文件到指定的目录
                        // 在下文中上传文件至数据库时,将对这里改写
                        item.write(new File(this.uploadPath+ path + name));
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }
            }
        }
    } catch (IOException e) {
        System.out.println(e);
    } catch (FileUploadException e) {
        System.out.println(e);
    }
}

/**
 * Initialization of the servlet. <br>
 *
 * @throws ServletException if an error occurs
 */
public void init() throws ServletException {
    this.uploadPath = this.getServletConfig().getInitParameter("upload_path");
    this.uploadtmpPath= this.getServletConfig().getInitParameter("upload_tmppath");
    this.tempPath=new File(this.uploadtmpPath);
}

}

“`
这样就可以将用户的文件上传到服务器,服务器将文件存在wen.xml配置的d://里

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值