欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 文件上传 之 好几种方式上传。(~ o ~)~zZ

程序员文章站 2024-02-19 11:10:46
...

从昨天开始吧,项目需要文件上传,想偷懒跳转页面然后提交上传文件。谁知道啊,谁知道。是要那种直接上传到服务器的那种,哇。稍微有点难度。就各种找我之前做的项目,看有没有合适的。
ps: 这几个项目所需的jar啊,css啊,什么的都在最下面的链接。
使用springmvc 上传 文件
1) 首先要搭好项目框架,需要有些spring的知识。
2) 其次就是开始搭框架啦。
1 创建一个 web项目。找到web.xml。

<servlet>

        <servlet-name>springMVC</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
                <param-name>contextConfigLocation</param-name>
                //你的springmvc配置文件所在地。
                <param-value>/WEB-INF/springmvc.xml</param-value>
        </init-param>
         //  加载顺序
        <load-on-startup>0</load-on-startup>
    </servlet>
    //配置拦截方式  为.do
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

2 配置好web.xml后,那就是配置springmvc的 配置文件,在WEB-INF下创建一个springmvc.xml文件。文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">



        <!-- 启动spring注解 -->
        <context:annotation-config />

        <!-- 启动扫描 -->
        <context:component-scan base-package="com.zrgk" />

        <!-- 启动SpringMVC的注解方式 -->
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />



        <!--  配置文件上传的解析器-->
        <bean id="multipartResolver"       
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver"       
          p:defaultEncoding="utf-8">
       </bean>


</beans>

3 在 WEB-INF 文件夹下在创建lib,引入所需的jar包。

commons-fileupload-1.2.1jar
commons-io-1.3.2.jar

4 在 WebRoot 下创建一个 upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'upload.jsp' starting page</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="UploadController.do" method="post" enctype="multipart/form-data">
           FILE: <input type="file" name="myFile" /><br/>
                 <input type="submit" value=" upload" />
       </form>
  </body>
</html>

5 创建 java 文件。

package com.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


@Controller
@RequestMapping("UploadController.do")
public class UploadController {


    @RequestMapping
    public String upload(HttpServletRequest request) throws Exception{
         //将当前上下文初始化给  
         CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
           //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                file.getName();
                if(file!=null)
                {
                    String path="E:/"+file.getOriginalFilename();
                    //上传
                    file.transferTo(new File(path));
                }

            }

        }



        return "upload.jsp";
    }

}

6 部署项目。
7 运行项目。
8 打开网址输入 127.0.0.1:端口号/你web项目名称/upload.jsp
ps:127.0.0.1:8088/springUpload/upload.jsp

使用 jq中的uploadify 来实现文件上传
ps: 这次使用的是 Java的servlet方式实现,uploadify功能也挺全,你们可以再看看文档。
1 创建一个 web项目
2 在 WEB-INF 文件夹下在创建lib,引入所需的jar包。

commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar

3 WebRoot 创建一个 plugin 文件夹,在 plugin 文件夹下 在创建一个uploadify 文件,在uploadify 文件中传入
1) jquery-1.11.3.js
2) jquery.uploadify.js
3) jquery.uploadify.min.js
4) uploadify-cancel.png
5) uploadify.css
6) uploadify.swf
4 将 index.jsp修改为以下的内容:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<link href="plugin/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
<script src="plugin/uploadify/jquery-1.11.3.js" type="text/javascript"></script>
<script src="plugin/uploadify/jquery.uploadify.js" type="text/javascript"></script>
<script type="text/javascript">  
$(document).ready(function() {  
    $("#uploadify").uploadify({  
          // uploadify 文件
        'swf'       : 'plugin/uploadify/uploadify.swf',  
        // 后台处理的 Servlet名称,(如果使用spring,那就是你指向的controllor。)
        'uploader'  : 'UploadServlet',    
        'folder'         : '/upload',  
        'queueID'        : 'fileQueue',
          //背景图
        'cancelImg'      : 'plugin/uploadify/uploadify-cancel.png',
        'buttonText'     : '上传文件',
        'auto'           : true, //设置true 自动上传 设置false还需要手动点击按钮 
        'multi'          : true,  
        'wmode'          : 'transparent',  
        'simUploadLimit' : 999,  
        'fileTypeExts'        : '*.*', 
        //所有类型文件 
        'fileTypeDesc'       : 'All Files'
    });  
});  

</script>  
</head>
<body>

    <div>
        <%--用来作为文件队列区域--%>
        <div id="fileQueue" style="position:absolute; right:50px; bottom:100px;z-index:999">
        </div>
        <input type="file" name="uploadify" id="uploadify"/>

    </div>

</body>
</html>

5 创建java 文件 就是 servlet .

package demo.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
import org.apache.commons.fileupload.util.Streams;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //获取真实目录
        File tempDirPath =new File(request.getSession().getServletContext().getRealPath("/")+"\\upload\\");  
        if(!tempDirPath.exists()){  
            tempDirPath.mkdirs();  
        }  

        DiskFileItemFactory fac = new DiskFileItemFactory();      
        ServletFileUpload upload = new ServletFileUpload(fac);      
        List<FileItem> fileList = null;      
        try {      
            fileList = upload.parseRequest(request);      
        } catch (FileUploadException ex) {      
            ex.printStackTrace();      
            return;      
        }   
        Iterator<FileItem> it = fileList.iterator();     
        while(it.hasNext()){      
            FileItem item =  it.next(); 
            if(!item.isFormField()){
                BufferedInputStream in = new BufferedInputStream(item.getInputStream());     
                BufferedOutputStream out = new BufferedOutputStream(        
                        new FileOutputStream(new File(tempDirPath+"\\"+item.getName())));  
                Streams.copy(in, out, true);  

            }  
        }  
        //  
        PrintWriter out = null;  
        try {  
            out = encodehead(request, response);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        out.close();   
    }

    /** 
     * @return 
     * @throws IOException  
     * @throws IOException  
     * request.setCharacterEncoding("utf-8"); 
        response.setContentType("text/html; charset=utf-8"); 
     */  

    private PrintWriter encodehead(HttpServletRequest request,HttpServletResponse response) throws IOException{  
        request.setCharacterEncoding("utf-8");  
        response.setContentType("text/html; charset=utf-8");  
        return response.getWriter();  
    }  
}

6 部署项目。
7 运行项目。

使用 百度 的webupload 上传文件
ps: 这次还借助第一个《使用springmvc 上传 文件》那个项目去上传。这个百度的upload还是很强大的。有各种形式的上传,老铁们可以去搜webload 看看文档什么的。

前面的步骤(1和2)还是不变。

3 在WebRoot文件夹下创建webload文件夹,将webUpload所需的文件放到这个文件夹下。
1) jquery-1.10.1.min.js
2) Uploader.swf
3) webuploader.css
4) webuploader.js
4 在WebRoot文件夹下创建 webUpload.jsp。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8" errorPage="true"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>webUpload</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">
    -->
 <link rel="stylesheet" type="text/css" href="http://127.0.0.1:8088/0425SpringMVC/webload/webuploader.css">  

    <script type="text/javascript" src="http://127.0.0.1:8088/0425SpringMVC/webload/jquery-1.10.1.min.js"></script>
        <script type="text/javascript" src="http://127.0.0.1:8088/0425SpringMVC/webload/webuploader.js"></script>
<script>


jQuery(function() {

  var $ = jQuery,

   $list = $('#thelist'),

      $btn = $('#ctlBtn'),

       state = 'pending',

     uploader;


   uploader = WebUploader.create({


      // 不压缩image

       resize: false,


     // swf文件路径

   swf: 'http://127.0.0.1:8088/0425SpringMVC/webload/Uploader.swf',


      // 文件接收服务端。

  server: 'UploadController.do',


     // 选择文件的按钮。可选。
        // 内部根据当前运行是创建,可能是input元素,也可能是flash.

      pick: '#picker'

    });


  // 当有文件添加进来的时候

  uploader.on( 'fileQueued', function( file ) {

     $list.append( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上传...</p>' +
        '</div>' );
    });


 // 文件上传过程中创建进度条实时显示。

   uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');


 // 避免重复创建

   if ( !$percent.length ) {

      $percent = $('<div class="progress progress-striped active">' +
              '<div class="progress-bar" role="progressbar" style="width: 0%">' +
              '</div>' +
            '</div>').appendTo( $li ).find('.progress-bar');
        }

        $li.find('p.state').text('上传中');

        $percent.css( 'width', percentage * 100 + '%' );
    });


   uploader.on( 'uploadSuccess', function( file ) {
        $( '#'+file.id ).find('p.state').text('已上传');
    });


  uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上传出错');
    });


  uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
    });


  uploader.on( 'all', function( type ) {
        if ( type === 'startUpload' ) {
            state = 'uploading';
        } 
else if ( type === 'stopUpload' ) {
            state = 'paused';
        }
 else if ( type === 'uploadFinished' ) {
            state = 'done';
        }


   if ( state === 'uploading' ) {

     $btn.text('暂停上传');
        } 
else {
            $btn.text('开始上传');
        }
    });


 $btn.on( 'click', function() {
        if ( state === 'uploading' ) {
            uploader.stop();
        } else {
            uploader.upload();
        }
    });
});
</script>
</head>

<body>

<div id="uploader" class="wu-example">
    <!--用来存放文件信息-->
    <div id="thelist" class="uploader-list"></div>
    <div class="btns">
        <div id="picker">选择文件</div>
        <button id="ctlBtn" class="btn btn-default">开始上传</button>
    </div>
</div>


</body>
</html>

5 写 java代码:
ps:这里使用的后台处理也是用的《使用springmvc 上传 文件》的后台。
6 项目部署。
7 运行项目。

嗯,目前就找到了这三种吧。希望可以蒙混过关。哎呀呀,忘了,忘了,还有jar,等等的链接。
百度云链接:
https://pan.baidu.com/s/1pL0xxeN