FileUpload的简单使用

1.首先要在Apache网站上下载如下两个包:

 

  将文件夹下的这两个jar引入到项目中

2.前台使用界面的编写:


<html>
    
<head>
        
<title>index.html</title>

        
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        
<meta http-equiv="description" content="this is my page">

        
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

    
</head>

    
<body>
        
<form action="../FileUpload" method="post" enctype="multipart/form-data" name="form1"> 
            
<input type="hidden" name="id" value="<%= id %>">
            
<input type="file" name="file">
            
<input type="submit" name="Submit" value="upload">
        
</form>
        
        
        
        
<form name="uploadform" method="POST" action="../FileUpload"    enctype="multipart/form-data">

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

                
<tr>
                    
<td width="100%" colspan="2">

                        文件1:
                        
<input name="x" size="40" type="file">

                    
</td>
                
</tr>

                
<tr>
                    
<td width="100%" colspan="2">

                        文件2:
                        
<input name="y" size="40" type="file">

                    
</td>
                
</tr>

                
<tr>
                    
<td width="100%" colspan="2">

                        文件3:
                        
<input name="z" size="40" type="file">

                    
</td>
                
</tr>

            
</table>

            
<br />
            
<br />

            
<table>

                
<tr>
                    
<td align="center">
                        
<input name="upload" type="submit" value="开始上传" />
                    
</td>
                
</tr>

            
</table>

        
</form>

    
</body>
</html>

 

效果如下图所示:

 

3.编写sevlet : FIleUpload.java(我让其在web.xml中接收一个初始化参数,此参数是上传文件存放的位置)

 

package com.ycringfinger.shopping.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
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;

public class FileUpload extends HttpServlet {

    
public void init(ServletConfig config) throws ServletException {
        uploadPath 
= config.getInitParameter("uploadpath");
    }


    String uploadPath 
= "";
    
    
public void destroy() {
        
super.destroy(); // Just puts "destroy" string in log
        
// Put your code here
    }


    
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType(
"text/html; charset=GB2312");
        
        
int id = -1;
        
        PrintWriter out 
= res.getWriter();
        
//System.out.println(req.getContentLength());
        
//System.out.println(req.getContentType());
        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()
        factory.setRepository(new File("d:/"));

        ServletFileUpload upload 
= new ServletFileUpload(factory);
        
// maximum size before a FileUploadException will be thrown
        upload.setSizeMax(1000000);
        
try {
            List fileItems 
= upload.parseRequest(req);
            
// assume we know there are two files. The first file is a small text file, the second is unknown and is written to a file on the server
            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()) {
                    
if(item.getFieldName().equals("id")) {
                        id 
= Integer.parseInt(item.getString());
                        
//System.out.println(id);
                    }

                }

                
                
// 忽略其他不是文件域的所有表单信息
                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) {
                        
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 + id + ".jpg"));

                            out.print(name 
+ "&nbsp;&nbsp;" + size + "<br>");
                        }
 catch (Exception e) {
                            out.println(e);
                        }


                    }
 else {
                        
throw new IOException("fail to upload");
                    }

                }

            }

        }
 catch (IOException e) {
            out.println(e);
        }
 catch (FileUploadException e) {
            out.println(e);
        }


        
// 保存上传的文件到指定的目录

        
// 在下文中上传文件至数据库时,将对这里改写

    }


    
public void init() throws ServletException {
        
    }


}

 

4.我的web.xml的配置(其中也包含了JFreeChart)

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
    xmlns
="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>
  
<servlet>
    
<description>FileUpload</description>
    
<display-name>FileUpload</display-name>
    
<servlet-name>FileUpload</servlet-name>
    
<servlet-class>com.ycringfinger.shopping.servlet.FileUpload</servlet-class>
    
<init-param>
        
<param-name>uploadpath</param-name>
        
<param-value>D:/JavaWork/Shopping/WebRoot/images/product/</param-value>
    
</init-param>
  
</servlet>
  
<servlet>
    
<servlet-name>ProductSalesChart</servlet-name>
    
<servlet-class>com.ycringfinger.shopping.chart.ProductSalesChart</servlet-class>
    
<init-param>
        
<param-name>generatedpath</param-name>
        
<param-value>D:/JavaWork/Shopping/WebRoot/images/productsales/</param-value>
    
</init-param>
  
</servlet>

  

  
<servlet-mapping>
    
<servlet-name>FileUpload</servlet-name>
    
<url-pattern>/FileUpload</url-pattern>
  
</servlet-mapping>
  
<servlet-mapping>
    
<servlet-name>ProductSalesChart</servlet-name>
    
<url-pattern>/ProductSalesChart</url-pattern>
  
</servlet-mapping>
    
</web-app>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值