java多文件上传显示进度条

Python017

java多文件上传显示进度条,第1张

使用   apache fileupload   ,spring MVC   jquery1.6x , bootstrap  实现一个带进度条的多文件上传,由于fileupload 的局限,暂不能实现每个上传文件都显示进度条,只能实现一个总的进度条,效果如图:

1、jsp 页面

<!DOCTYPE html>  

<%@ page contentType="text/htmlcharset=UTF-8"%>    

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    

<html xmlns="http://www.w3.org/1999/xhtml">  

<head>  

<meta http-equiv="Content-Type" content="text/html charset=UTF-8" />  

<script src="../js/jquery-1.6.4.js" type="text/javascript"></script>  

<link rel="stylesheet" type="text/css" href="../css/bootstrap.css"/>  

</head>  

<body>  

        <form id='fForm' class="form-actions form-horizontal" action="../upload.html"   

              encType="multipart/form-data" target="uploadf" method="post">  

                 <div class="control-group">  

                    <label class="control-label">上传文件:</label>  

                    <div class="controls">  

                        <input type="file"  name="file" style="width:550">  

                              

                    </div>  

                    <div class="controls">  

                        <input type="file"  name="file" style="width:550">  

                    </div>  

                    <div class="controls">  

                        <input type="file"  name="file" style="width:550">  

                    </div>  

                    <label class="control-label">上传进度:</label>  

                    <div class="controls">  

                        <div  class="progress progress-success progress-striped" style="width:50%">  

                            <div  id = 'proBar' class="bar" style="width: 0%"></div>  

                        </div>  

                    </div>  

                </div>  

                  

                 <div class="control-group">  

                    <div class="controls">  

                    <button type="button" id="subbut" class="btn">submit</button>  

                    </div>  

                </div>  

        </form>  

        <iframe name="uploadf" style="display:none"></iframe>  

</body>  

</html>  

<script >  

$(document).ready(function(){  

    $('#subbut').bind('click',  

            function(){  

                $('#fForm').submit()  

                var eventFun = function(){  

                    $.ajax({  

                        type: 'GET',  

                        url: '../process.json',  

                        data: {},  

                        dataType: 'json',  

                        success : function(data){  

                                $('#proBar').css('width',data.rate+''+'%')  

                                $('#proBar').empty()  

                                $('#proBar').append(data.show)   

                                if(data.rate == 100){  

                                    window.clearInterval(intId)  

                                }     

                }})}  

                var intId = window.setInterval(eventFun,500)  

    })  

})  

</script>

2、java 代码

package com.controller  

  

import java.util.List  

  

import javax.servlet.http.HttpServletRequest  

import javax.servlet.http.HttpServletResponse  

import javax.servlet.http.HttpSession  

  

import org.apache.commons.fileupload.FileItemFactory  

import org.apache.commons.fileupload.ProgressListener  

import org.apache.commons.fileupload.disk.DiskFileItemFactory  

import org.apache.commons.fileupload.servlet.ServletFileUpload  

import org.apache.log4j.Logger  

import org.springframework.stereotype.Controller  

import org.springframework.web.bind.annotation.RequestMapping  

import org.springframework.web.bind.annotation.RequestMethod  

import org.springframework.web.bind.annotation.ResponseBody  

import org.springframework.web.servlet.ModelAndView  

  

@Controller  

public class FileUploadController {  

    Logger log = Logger.getLogger(FileUploadController.class)  

      

    /** 

     * upload  上传文件 

     * @param request 

     * @param response 

     * @return 

     * @throws Exception 

     */  

    @RequestMapping(value = "/upload.html", method = RequestMethod.POST)  

    public ModelAndView upload(HttpServletRequest request,  

            HttpServletResponse response) throws Exception {  

        final HttpSession hs = request.getSession()  

        ModelAndView mv = new ModelAndView()  

        boolean isMultipart = ServletFileUpload.isMultipartContent(request)  

        if(!isMultipart){  

            return mv  

        }  

        // Create a factory for disk-based file items  

        FileItemFactory factory = new DiskFileItemFactory()  

  

        // Create a new file upload handler  

        ServletFileUpload upload = new ServletFileUpload(factory)  

        upload.setProgressListener(new ProgressListener(){  

               public void update(long pBytesRead, long pContentLength, int pItems) {  

                   ProcessInfo pri = new ProcessInfo()  

                   pri.itemNum = pItems  

                   pri.readSize = pBytesRead  

                   pri.totalSize = pContentLength  

                   pri.show = pBytesRead+"/"+pContentLength+" byte"  

                   pri.rate = Math.round(new Float(pBytesRead) / new Float(pContentLength)*100)  

                   hs.setAttribute("proInfo", pri)  

               }  

            })  

        List items = upload.parseRequest(request)  

        // Parse the request  

        // Process the uploaded items  

//      Iterator 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("this is common feild!"+name+"="+value)  

//          } else {  

//              System.out.println("this is file feild!")  

//               String fieldName = item.getFieldName()  

//                  String fileName = item.getName()  

//                  String contentType = item.getContentType()  

//                  boolean isInMemory = item.isInMemory()  

//                  long sizeInBytes = item.getSize()  

//                  File uploadedFile = new File("c://"+fileName)  

//                  item.write(uploadedFile)  

//          }  

//      }  

        return mv  

    }  

      

      

    /** 

     * process 获取进度 

     * @param request 

     * @param response 

     * @return 

     * @throws Exception 

     */  

    @RequestMapping(value = "/process.json", method = RequestMethod.GET)  

    @ResponseBody  

    public Object process(HttpServletRequest request,  

            HttpServletResponse response) throws Exception {  

        return ( ProcessInfo)request.getSession().getAttribute("proInfo")  

    }  

      

    class ProcessInfo{  

        public long totalSize = 1  

        public long readSize = 0  

        public String show = ""  

        public int itemNum = 0  

        public int rate = 0  

    }  

      

}

java get方式异步上传_简述Java异步上传文件的三种方式 原创

2021-02-13 16:31:03

yi bbbian

码龄4年

关注

本文为大家分享了三种Java异步上传文件方式,供大家参考,具体内容如下

用第三方控件,如Flash,ActiveX等浏览器插件上传。

使用隐藏的iframe模拟异步上传。

使用XMLHttpRequest2来实现异步上传。

第一种使用浏览器插件上传,需要一定的底层编码功底,在这里我就不讲了,以免误人子弟,提出这点大家可以自行百度。

第二种使用隐藏的iframe模拟异步上传。为什么在这里说的是模拟呢?因为我们其实是将返回结果放在了一个隐藏的iframe中,所以才没有使当前页面跳转,感觉就像是异步操作一样。

隐藏的iframe上传文件

附件:

正在上传...

// 上传完成后的回调

function uploadFinished(fileName) {

addToFlist(fileName)

loading(false)

}

function addToFlist(fname) {

var temp = ["

",

fname,

"删除",

"

"

]

$("#flist").append(temp.join(""))

}

function loading(showloading) {

if (showloading) {

$("#uptxt").show()

} else {

$("#uptxt").hide

}

}

这种技术有两个关键的地方:

1.form会指定target,提交的结果定向返回到隐藏的ifram中。(即form的target与iframe的name属性一致)。

2.提交完成后,iframe中页面与主页面通信,通知上传结果及服务端文件信息

如何与主页面通信呢?

我们用nodejs在接收完了文件后返回了一个window.parent.主页面定义的方法,执行后可以得知文件上传完成。代码很简单:

router.post('/upload2', multipartMiddleware, function(req, res) {

var fpath = req.files.myfile.path

var fname = fpath.substr(fpath.lastIndexOf('\\') + 1)

setTimeout(function {

var ret = ["

"window.parent.uploadFinished('" + fname + "')",

""]

res.send(ret.join(""))

}, 3000)

})

执行后可以打开开发人员选项,你会发现隐藏iframe中返回了服务器的一些数据。

第三种使用XMLHttpRequest2来进行真正的异步上传。

还是先贴出代码:

执行后可以打开开发人员选项,你会发现隐藏iframe中返回了服务器的一些数据。第三种使用XMLHttpRequest2来进行真正的异步上传。还是先贴出代码:

xhr level2 异步上传

附件:

正在上传...

停止上传

function upload {

// 1.准备FormData

var fd = new FormData

fd.append("myfile", $("#myfile")[0].files[0])

// 创建xhr对象

var xhr = new XMLHttpRequest

// 监听状态,实时响应

// xhr 和 xhr.upload 都有progress事件,xhr.progress是下载进度,xhr.upload.progress是上传进度

xhr.upload.onprogress = function(event) {

if (event.lengthComputable) {

var percent = Math.round(event.loaded * 100 / event.total)

console.log('%d%', percent)

$("#upprog").text(percent)

}

}

// 传输开始事件

xhr.onloadstart = function(event) {

console.log('load start')

$("#upprog").text('开始上传')

$("#stopbtn").one('click', function { xhr.abort$(this).hide()})

loading(true)

}

// ajax过程成功完成事件

xhr.onload = function(event) {

console.log('load success')

$("#upprog").text('上传成功')

console.log(xhr.responseText)

var ret = JSON.parse(xhr.responseText)

addToFlist(ret.fname)

}

// ajax过程发生错误事件

xhr.onerror = function(event) {

console.log('error')

$("#upprog").text('发生错误')

}

// ajax被取消

xhr.onabort = function(event) {

console.log('abort')

$("#upprog").text('操作被取消')

}

// loadend传输结束,不管成功失败都会被触发

xhr.onloadend = function (event) {

console.log('load end')

loading(false)

}

// 发起ajax请求传送数据

xhr.open('POST', '/upload3', true)

xhr.send(fd)

}

function addToFlist(fname) {

var temp = ["

",

fname,

"删除",

"

"

]

$("#flist").append(temp.join(""))

}

function delFile(fname) {

console.log('to delete file: ' + fname)

// TODO: 请实现

}

function loading(showloading) {

if (showloading) {

$("#uptxt").show()

$("#stopbtn").show()

} else {

$("#uptxt").hide()

$("#stopbtn").hide()

}

}

代码有点多,但是通俗易懂。使用过AJAX的人都知道,XHR对象提供了一个onreadystatechange的回调方法来监听整个请求/响应过程。在XMLHttpRequest2级规范中又多了几个进度事件。有以下6个事件:

1.loadstart:在接收到响应数据的第一个字节时触发。

2.progress:在接收响应期间持续不断地触发。

3.error:在请求发生错误时触发。

4.abort:在因为调用abort方法而终止连接时触发。

5.load:在接收到完整的响应数据时触发。

6.loadend: 在通信完成或者触发error,abort,load事件后触发。

这次我们可以解读代码:当传输事件开始后,我们便在停止传送按钮上添加点击事件,内置了abort方法可以停止传送。若不点则会正常上传直到传送完毕为止。其后台代码类似第二种方法。

三种方法各有优劣,做个简单的小结吧。

第三方控件交互性和可控性好,因为接近底层,其性能也是很优秀的。但是由于编写难度大通常需要自己安装插件,有时可能需要自己进行编写。

隐藏的iframe方法我个人觉得是非常有思想的一个方法,iframe可以帮我们做很多事。这种方式具有广泛的浏览器兼容性而且不需要安装插件。但是它交互性差,上传过程不可控,而且性能也是很一般的。

XHR2级的纯ajax上传,它必须要版本比较高一点的浏览器(ie9+)。但是它交互性特别好,可以看到上传进度并且是可控的。