您的位置:首页 > Web前端 > JavaScript

ajax进度条(附加限制大小在jsp页面)

2018-01-15 13:39 337 查看
===========================================进度条的实体类=================================

package com.work.oa.sys.domain;

import java.io.Serializable;

public class Progress implements Serializable{

    private long pBytesRead;

    private long pContentLength;

    private long pItems;

    public long getpBytesRead() {

        return pBytesRead;

    }

    public void setpBytesRead(long pBytesRead) {

        this.pBytesRead = pBytesRead;

    }

    public long getpContentLength() {

        return pContentLength;

    }

    public void setpContentLength(long pContentLength) {

        this.pContentLength = pContentLength;

    }

    public long getpItems() {

        return pItems;

    }

    public void setpItems(long pItems) {

        this.pItems = pItems;

    }

    @Override

    public String toString() {

        return "Progress [pBytesRead=" + pBytesRead + ", pContentLength="

                + pContentLength + ", pItems=" + pItems + "]";

    }

}

================================上传时重写CommonsMultipartResolver的方法(用来set进度条的数据)===============

package com.work.oa.sys.listener;

import java.util.List;

import javax.servlet
4000
.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUpload;

import org.apache.commons.fileupload.FileUploadBase;

import org.apache.commons.fileupload.FileUploadException;

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

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.multipart.MaxUploadSizeExceededException;

import org.springframework.web.multipart.MultipartException;

import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class CustomMultipartResolver extends CommonsMultipartResolver {

    @Autowired

    private FileUploadProgressListener progressListener;

    public void setFileUploadProgressListener(

            FileUploadProgressListener progressListener) {

        this.progressListener = progressListener;

    }

    @Override

    @SuppressWarnings("unchecked")

    public MultipartParsingResult parseRequest(HttpServletRequest request)

            throws MultipartException {

        String encoding = determineEncoding(request);

        FileUpload fileUpload = prepareFileUpload(encoding);

        progressListener.setSession(request.getSession());

        fileUpload.setProgressListener(progressListener);

        try {

            List<FileItem> fileItems = ((ServletFileUpload) fileUpload)

                    .parseRequest(request);

            return parseFileItems(fileItems, encoding);

        } catch (FileUploadBase.SizeLimitExceededException ex) {

            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(),

                    ex);

        } catch (FileUploadException ex) {

            throw new MultipartException(

                    "Could not parse multipart servlet request", ex);

        }

    }

}

============================================设置进度条的数据=============================

package com.work.oa.sys.listener;

import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.ProgressListener;

import org.springframework.stereotype.Component;

import com.work.oa.sys.domain.Progress;

@Component

public class FileUploadProgressListener implements ProgressListener {

    private HttpSession session;

    public void setSession(HttpSession session) {

        this.session = session;

        Progress status = new Progress();// 保存上传状态

        session.setAttribute("status", status);

    }

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

        Progress status = (Progress) session.getAttribute("status");

        try {

            Thread.sleep(5);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        status.setpBytesRead(pBytesRead);

        status.setpContentLength(pContentLength);

        status.setpItems(pItems);

    }

}

==========================================spring的相关配置========================================

    <!-- 配置多文件上传 -->

    <bean id="multipartResolver"

        <!-- 自定义的类-->

        class="com.work.oa.sys.listener.CustomMultipartResolver">

        <property name="defaultEncoding">

            <value>UTF-8</value>

        </property>

        <property name="maxUploadSize">

            <!-- 上传文件大小限制为31M,31*1024*1024 -->

            <value>32505856</value>

        </property>

        <property name="maxInMemorySize">

            <value>4096</value>

        </property>

    </bean>

<!--一定要扫描对应的包-->

<context:component-scan base-package="com.work.oa.sys.listener" />

=========================================jsp页面的部分======================================

$("#confirm").click(function(){

            var formData = new FormData($("#taskAddForm")[0]);

        //一秒执行一次

            var t1 = window.setInterval(uploadTime,1000);

            $.ajax({  

                  url: '${ctx}/taskAdd',

                  type: 'POST',  

                  data: formData,  

                  contentType: false,  

                  processData: false,

                  dataType : "json",

                  success: function (data) {  

                    if(data.success){

                        //停止执行

                        window.clearInterval(t1);

                         layer.msg(data.msg);

                         setTimeout(function(){

                           location.href = "${ctx}/toTaskList?projectId=${projectId}";

                        }, 500);

                    }else{

                        $("#confirm").attr("disabled", false);

                        layer.msg(data.msg);                            

                    }  

                  }

             });

        });

        

    });

//获取上传进度

function uploadTime() {

        $.ajax({  

             url: '${ctx}/getProgress',

             type: 'POST',  

             dataType : "json",

             success: function (data) {

                 if(data.success){

                     layer.msg("上传进度:"+Number(data.pBytesRead/data.pContentLength*100).toFixed(2)+"%");

                 }else{

                     layer.msg(data.msg);

                 }

             }

        });

      }

//上传不能超过31M

    function checkFileSize(targetFile) {

        var submitButton = $("#confirm");

        if (targetFile.files && targetFile.files[0]) {

            var fileSize = targetFile.files[0].size/1024.0/1024;

            if(fileSize>31){

                layer.msg("上传的文件不能大于31MB!!!");

                $("#confirm").attr("disabled", true);

            }else{

                $("#confirm").attr("disabled", false);

            }

        }

    }

============================================上传的相关代码================================

@RequestMapping("taskAdd")

    @ResponseBody

    public Map taskAdd(HttpServletRequest request,@RequestParam List<MultipartFile> file2,Task task){

        Map map = Maps.newHashMap();

        if(null==task.getTaskCode()||"".equals(task.getTaskCode())){

            //获取taskcode

            String taskCode = taskService.getNoRepeatTask();

            task.setTaskCode(taskCode);

        }

        try{

            List<MultipartFile> files = file2;

            String path = "";

            for(MultipartFile file:files){

                String fileName = task.getTaskCode()+"-"+System.currentTimeMillis();

                String assetsPicName =  Constants.SEPARATOR + fileName+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

                String filePath = Constants.TASK_DATA_PATH;

                File dir = new File(filePath);

                if(!dir.exists()) dir.mkdirs();

                File fileUrl = new File(filePath + assetsPicName);

-----------------------------------------------主要是下面这句->上传------------------

                file.transferTo(fileUrl); //上传图片

--------------------------------------------------------------------------------------

                path+=";"+filePath + assetsPicName;

            }

            if(!path.isEmpty()){

                task.setTaskDataPath(path.substring(1));

            }

            taskService.insertTask(task);

            map.put(Constants.SUCCESS, true);

            map.put(Constants.MSG, "任务添加成功");

        }catch (Exception e) {

            map.put(Constants.SUCCESS, false);

            map.put(Constants.MSG, "系统异常,任务添加失败");

            logger.error("添加任务失败:" + e.getMessage());

        }

        return map;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: