代码改变世界

文件的上传

2017-01-06 20:28  甘雨路  阅读(192)  评论(0编辑  收藏  举报
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">


    <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>com.zr.uploaddownload.servlet.UploadServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/UploadServlet</url-pattern>
    </servlet-mapping>

</web-app>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>



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

  </head>
  
  <body>
    
    <form action="UploadServlet" method="post" enctype="multipart/form-data">
        上传文件:<input type="file" name="file"/><br><br>
        <span>文件介绍:</span><br>
        <textarea rows="5" cols="35" name="text"></textarea>
        <br><br>
        <input type="submit" value="提交">
    </form>    

  </body>
</html>
package com.zr.uploaddownload.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

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

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;
/**
 * 
 * @author lf
 *
 */
public class UploadServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

//        System.out.println("UploadServlet...doPost...");
        
        //设置编码(应该在filter进行设置编码)
        /*req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");*/

        // 创建DiskFileItem工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 设置内存大小
        factory.setSizeThreshold(1024*1024);
        //设置超出内存大小时,文件的临时存放路径
        factory.setRepository(new File("D:\\tempFile"));

        // 创建上传的对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置单个文件上传的最大值(5M)
        upload.setSizeMax(1024*1024*5);

        List<FileItem> items = null;
        try {
            // 解析请求
            items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                   //文本域处理
                    String name = item.getFieldName();
                    String value = item.getString();
                    System.out.println("name:"+name+"\nvalue:"+value);
                    
                } else {
                    //文件域处理
                    String fieldName = item.getFieldName();
                    //获取文件名
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    
                    System.out.println("fieldName:"+fieldName
                            +"\nfileName"+fileName+"\ncontentType"
                            +contentType+"\nisInMemory"+isInMemory
                            +"\nsizeInBytes"+sizeInBytes);
                    
                    //文件名
                    String name = fileName.substring(fileName.indexOf("."));
                    //通过随机数产生文件名
                    String str = new Date().getTime()+""+(int)Math.random()*10000;
                    //上传文件保存的路径
                    String path = "D:\\"+str+name;
                    File uploadedFile = new File(path);
                    // 将路径写入数据库(在此不进行写入数据库的操作)
                    try {
                        item.write(uploadedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        
        
        
    }
}