文件上传的步骤

文件上传的步骤:
1.<input type="file" />
2.首先要更改form的enctype="multipart/form-data"
表示向服务器传输的过程中以二进制的方式传输
默认传输类型: enctype="application/x-www-form-urlencoded"
3.相关jar包 下载地址 www.apache.org
commons-fileupload-1.2.1.jar 核心组件包
commons-io-2.0.1.jar --fileupload组件包,依赖了IO
commons-lang3-3.1.jar
commons-logging-1.1.3.jar

json-lib-2.4-jdk15.jar JSON工具类
struts2-json-plugin-2.3.15.1.jar

4.普通上传页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>文件上传的开发</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <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="upload/uploadAction.jsp?dirpath=pipi" method="post" enctype="multipart/form-data">
        <p><input type="text" name="username" value="pipi" /></p>
        <p><input type="file" name="file000" /></p>
        <input type="submit" value="提交" />
    </form>
    
  </body>
</html>

5.ajax上传页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
  <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>ajax文件上传的开发</title>
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
        #percent{width:600px;height:30px;position:relative;border:1px solid green;}
        #percent #per{height:30px;background:green;position:absolute;left:0;top:0;}
    </style>
  </head>
  
  <body>
    <form action="upload/uploadAction.jsp?dirpath=pipi" method="post" enctype="multipart/form-data">
        <a href="javascript:;" class="uploadbtn" onclick="openFileDialog()">文件上传</a>
        <input type="file" name="file" id="file" onchange="uploadFile()" style="display: none;" />
        <input type="submit" value="提交" />
    </form>
    
    <img id="showImg" width="160" height="120" />
    <ul id="showlist">
    
    </ul>
    
    
    <div id="percent">
        <div id="per"></div>
    </div>
    <div id="pnum"></div>
    <script type="text/javascript">
        function openFileDialog(){
            var ie = navigator.appName == "Microsoft Internet Explorer"?true:false;
            if(ie){
                //如果是ie浏览器
                document.getElementById("file").click();
            }else{
                //自定义事件es5中的内容
                var a = document.createEvent("MouseEvents");
                a.initEvent("click",true,true);
                document.getElementById("file").dispatchEvent(a);
            }
        };
        
        
        
        //ajax文件上传  不支持低版本浏览器
        function uploadFile(){
            //拿到文件上传的队列
            var files = document.getElementById("file").files
            var file = files[0];
            
            var type = file.type;//文件类型
            var name = file.name;//文件名称
            var size = file.size;//文件大小
            if(type.indexOf("image") == -1) {
                alert("请上传图片类型")
                return;
            }
            //alert(file.name+"===="+file.size+"==="+file.type);
            showImage(file,function(data){
                document.getElementById("showImg").src=data;
            })
            
            var form = new FormData();
            form.append("file",file);
            
            //如何传输给服务器端,进度条
            var xhr = new XMLHttpRequest();
            //请求服务器
            xhr.open("post", "upload/uploadAction.jsp?dirpath=pipi",true);
            xhr.onreadystatechange = function(){
                if(this.readyState == 4 && this.status == 200){
                    var data = this.responseText;
                    
                    var jsonData = eval("("+data+")");
                    var html = "";
                    for(var i=0;i<jsonData.length;i++){
                        html += "<li>"+jsonData[i].name+"===="+jsonData[i].sizeString+"====<img src='"+jsonData[i].url+"' width='50' height='50'/>"
                    }
                    console.log(data);
                    document.getElementById("showlist").innerHTML += html;
                }
            };
            
            xhr.upload.addEventListener("progress", progressFunction,false);
            xhr.send(form);
            
        }
        
        //进度条
        function progressFunction(evt){
        console.log("------");
            var perDom = document.getElementById("per");
            if(evt.lengthComputable){
                //evt.loaded已经上传了多少
                //event.total上传文件的总大小
                var p = evt.loaded / event.total;
                console.log(p);
                var pnum = Math.floor(p*100) +"%";
                perDom.style.width = pnum;
                document.getElementById("pnum").innerHTML = pnum;
            }
        }
        
        /*图片预览*/
        function showImage(f,callback){
            var reader = new FileReader();  
            reader.onload = (function(theFile) {  
                return function(e) {  
                    // img 元素  
                    if(callback)callback(e.target.result);
                };  
      
            })(f);  
            reader.readAsDataURL(f);  
        };    
        
    </script>
  </body>
</html>

6.后台处理类

<%@page import="org.apache.struts2.json.JSONUtil"%>
<%@page import="com.rui.util.StrUtils"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    
    /*文件上传的方式*/
    
    //1.获取文件上传的工厂类
    FileItemFactory factory = new DiskFileItemFactory();
    //2.解析上传文件的工厂
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    //3.通过解析类解析request对象中的二进制文件
    List<FileItem> fileItems = fileUpload.parseRequest(request);
    //4.读取二进制文件,写入服务器
    
    //获取服务器的路径getRealPath()获取当前项目所在服务器的根目录 
    //D:tooldevapache-tomcat-7.0.56-windows-x86apache-tomcat-7.0.56me-webappsfileUploadresource
    String dirpath = request.getParameter("dirpath");//
    if(StrUtils.isEmpty(dirpath)) dirpath = "default";
    String fpath = "resource/"+dirpath;
    String path = request.getRealPath(fpath);
    File rootPath = new File(path);
    //如果目录不存在就动态创建
    if(!rootPath.exists()){
        rootPath.mkdirs();
    }
    
    //如果有文件,就开始进行读和写
    if(fileItems != null && fileItems.size()>0){
        List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
        for(FileItem fileItem : fileItems){
            if(!fileItem.isFormField()){//判断是不是file表单
                //获取文件名称
                String filename = fileItem.getName();
                //文件大小
                long filesize = fileItem.getSize();
                //获取文件后缀
                String ext = StrUtils.getExt(filename, true);
                //重构文件的名称===头像上传的原理就是文件的覆盖
                String fname = UUID.randomUUID().toString()+ext;
                File fileName = new File(rootPath,fname);
                fileItem.write(fileName);
                
                Map<String,Object> map = new HashMap<String,Object>(); 
                map.put("name", filename);
                map.put("size", filesize);
                map.put("sizeString", StrUtils.countFileSize(filesize));
                map.put("url", fpath+"/"+fname);
                maps.add(map);
                
            }
        }
        out.print(JSONUtil.serialize(maps));
    }else {
        out.print("");
        //response.sendRedirect("fail.jsp");
    }    
    //5.在服务器创建一个上传的目录
    //6.开始写入
    //7.返回数据
    
    //response.sendRedirect("success.jsp");
    
 %>

7.工具类

package com.rui.util;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 
 * @ClassName: StrUtils
 * @Description: 工具类
 * @author poseidon
 * @date 2015年10月23日 下午8:13:45
 * @version V1.0.0
 */
public class StrUtils {


    /**
     * 
     * @Title: isEmpty
     * @Description: 空判断 
     * @param content
     * @return boolean
     */
    public static boolean isEmpty(String content){
        return (content==null || content.equals(""))?true:false;
    }
    
    /**
     * 
     * @Title: isNotEmpty
     * @Description: 非空判断
     * @param content
     * @return boolean
     */
    public static boolean isNotEmpty(String content){
        return !isEmpty(content);
    }
    
    
    /**
     * 
     * @Title: formatDate
     * @Description: 格式化日期类
     * @param date
     * @param pattern
     * @return String
     */
    public static String formatDate(Date date,String pattern){
        if(date!=null){
            String dateString = new SimpleDateFormat(pattern).format(date);
            return dateString;
        }else{
            return "";
        }
    }
    
    /**
     * 
     * @Title: getExt
     * @Description: 获取文件的后缀
     * @param name 文件名称
     * @param flag true有点false没点
     * @return String
     */
    public static String getExt(String name,boolean flag){
        if(isNotEmpty(name)){
            String ext  = null;
            if(flag){
                ext = name.substring(name.lastIndexOf("."), name.length());
            }else{
                ext = name.substring(name.lastIndexOf(".")+1, name.length());
            }
            return ext;
        }else{
            return "";
        }
    }
    
    /**
     * 
     * @Title: generateFileName
     * @Description: 为上传文件自动分配文件名称,避免重复
     * @param fileName
     * @param randomNum
     * @param dataPattern
     * @return String
     */
    public static String generateFileName(String fileName,int randomNum,String dataPattern) {
        // 获得当前时间
        DateFormat format = new SimpleDateFormat(dataPattern);
        // 转换为字符串
        String formatDate = format.format(new Date());
        // 随机生成文件编号
        int random = new Random().nextInt(randomNum);
        // 获得文件后缀名称
        int position = fileName.lastIndexOf(".");
        String extension = fileName.substring(position);
        // 组成一个新的文件名称
        return formatDate + random + extension;
    }
    
    
    /**
     * 
     * @Title: countFileSize
     * @Description: 根据File文件的长度统计文件的大小
     * @param fileSize
     * @return String
     */
    public static String countFileSize(long fileSize) {
        String fileSizeString = "";
        try {
            DecimalFormat df = new DecimalFormat("#.00");
            long fileS = fileSize;
            if (fileS == 0) {
                fileSizeString = "0KB";
            } else if (fileS < 1024) {
                fileSizeString = df.format((double) fileS) + "B";
            } else if (fileS < 1048576) {
                fileSizeString = df.format((double) fileS / 1024) + "KB";
            } else if (fileS < 1073741824) {
                fileSizeString = df
                        .format(((double) fileS / 1024 / 1024) - 0.01)
                        + "MB";
            } else {
                fileSizeString = df.format((double) fileS / 1024 / 1024 / 1024)
                        + "G";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileSizeString;
    }
    
    /**
     * 
     * @Title: conversionSpecialCharacters
     * @Description: 把两个反斜线转换成正斜线
     * @param string
     * @return String
     */
    public static String conversionSpecialCharacters(String string) {
        return string.replaceAll("\\", "/");
    }

    public static void main(String[] args) {
        
        
    }
}
原文地址:https://www.cnblogs.com/sun-rain/p/5203180.html