文件上传速度

接口支持


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.osvue.win.app.common.ResultBean;

@RequestMapping("attachment")
@RestController
public class UploaderController {

	
	@RequestMapping("upload")
	public ResultBean upload(HttpServletRequest request)   {
		
		try {
			// 1.创建创建DiskFileItemFactory工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			String tempPath = "/";// 临时文件路径
			factory.setRepository(new File(tempPath));// 设置临时文件目录
			factory.setSizeThreshold(1024 * 1024 * 10);// 设置使用临时存储的阀值,单位字节
			/*
			 * 或者 DiskFileItemFactory factory = new DiskFileItemFactory(1024 *
			 * 100,new File(tempPath));
			 */
			// 2.创建文件解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");// 解决上传文件乱码问题
			upload.setFileSizeMax(1024 * 1024 * 50L); // 设置上传单个文件的大小的最大值,目前是设置为1024*1024*50字节,也就是50MB
			upload.setSizeMax(1024 * 1024 * 50L);// 设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为50MB
			List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));

			
			InputStream in = null;
			for (FileItem fileItem : items) {
				if (fileItem.isFormField()) {
					// 如果是普通表单字段
					String name = fileItem.getFieldName();
					String value = fileItem.getString();
					System.out.println(name +"---"+ value);
				} else {
					in = fileItem.getInputStream();
				}
			}
			if (in != null) {
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				int len = 0;
				while ((len = in.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
				// 关闭流
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				String str = out.toString();
				Thread.sleep(5000); 
				System.out.println(str);
				 
			}
			
		} catch ( Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ResultBean.ok().put("success", "hello00");
	}
}

planA

<!DOCTYPE html>
  <html>
  <head>
    <meta charset="UTF-8" />
  <title>XMLHttpRequest上传文件</title>
  <script type="text/javascript">
      //图片上传
  var xhr;
 
      //上传文件方法
 
      function UpladFile() {
        var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
 
        var url =  "/attachment/upload"; // 接收上传文件的后台地址
 
        var form = new FormData(); // FormData 对象
 
        form.append("file", fileObj); // 文件对象
 
        xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
 
        xhr.open("post", url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
 
        xhr.onload = uploadComplete; //请求完成
 
        xhr.onerror = uploadFailed; //请求失败
 
        xhr.upload.onprogress = progressFunction; //【上传进度调用方法实现】
 
        xhr.upload.onloadstart = function () {
          //上传开始执行方法
 
          ot = new Date().getTime(); //设置上传开始时间
 
          oloaded = 0; //设置上传开始时,以上传的文件大小为0
        };
 
        xhr.send(form); //开始上传,发送form数据
      }
 
      //上传成功响应
 
      function uploadComplete(evt) {
        //服务断接收完文件返回的结果
 
        var data = JSON.parse(evt.target.responseText);
 
        if (data.success) {
          alert("上传成功!");
        } else {
          alert("上传失败!");
        }
      }
 
      //上传失败
 
      function uploadFailed(evt) {
        alert("上传失败!");
      }
 
      //取消上传
 
      function cancleUploadFile() {
        xhr.abort();
      }
 
      //上传进度实现方法,上传过程中会频繁调用该方法
 
      function progressFunction(evt) {
        var progressBar = document.getElementById("progressBar");
 
        var percentageDiv = document.getElementById("percentage");
 
        // event.total是需要传输的总字节,event.loaded是已经传输的字节。如果event.lengthComputable不为真,则event.total等于0
 
        if (evt.lengthComputable) {
          //
 
          progressBar.max = evt.total;
 
          progressBar.value = evt.loaded;
 
          percentageDiv.innerHTML =
            Math.round((evt.loaded / evt.total) * 100) + "%";
        }
 
        var time = document.getElementById("time");
 
        var nt = new Date().getTime(); //获取当前时间
 
        var pertime = (nt - ot) / 1000; //计算出上次调用该方法时到现在的时间差,单位为s
 
        ot = new Date().getTime(); //重新赋值时间,用于下次计算
 
        var perload = evt.loaded - oloaded; //计算该分段上传的文件大小,单位b
 
        oloaded = evt.loaded; //重新赋值已上传文件大小,用以下次计算
 
        //上传速度计算
 
        var speed = perload / pertime; //单位b/s
 
        var bspeed = speed;
 
        var units = "b/s"; //单位名称
 
        if (speed / 1024 > 1) {
          speed = speed / 1024;
 
          units = "k/s";
        }
 
        if (speed / 1024 > 1) {
          speed = speed / 1024;
 
          units = "M/s";
        }
 
        speed = speed.toFixed(1);
 
        //剩余时间
 
        var resttime = ((evt.total - evt.loaded) / bspeed).toFixed(1);
 
        time.innerHTML =
          ",速度:" + speed + units + ",剩余时间:" + resttime + "s";
 
        if (bspeed == 0) time.innerHTML = "上传已取消";
      }
    </script>
  </head>
 
  <body>
    <progress
      id="progressBar"
      value="0"
      max="100"
      style="width: 300px"
    ></progress>
 
    <span id="percentage"></span><span id="time"></span>
 
    <br /><br />
 
    <input type="file" id="file" name="myfile" />
 
    <input type="button" οnclick="UpladFile()" value="上传" />
 
    <input type="button" οnclick="cancleUploadFile()" value="取消" />
  </body>
</html>

planB

<!doctype html>
 <html lang="en">

 <head>
     <meta charset="UTF-8">
     <meta name="viewport"
         content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title>Document</title>
     <style>
         #progress {
             height: 10px;
             width: 500px;
             border: 1px solid gold;
             position: relative;
             border-radius: 5px;
         }

         #progress .progress-item {
             height: 100%;
             position: absolute;
             left: 0;
             top: 0;
             background: chartreuse;
             border-radius: 5px;
             transition: width .3s linear;
         }
     </style>
 </head>

 <body>
     文件上传框<br>
     <input type="file" id="file"><br>
     显示进度条<br>
     <div id="progress">
         <div class="progress-item"></div>
     </div>
     上传成功后的返回内容<br>
     <span id="callback"></span>
     <button onclick="upload()">上传文件</button>
 </body>
 <script>
     //首先监听input框的变动,选中一个新的文件会触发change事件
     document.querySelector("#file").addEventListener("change",
         (e) => {
             console.log(e)
         }
     );


     function upload() {
         //获取到选中的文件
         var file = document.querySelector("#file").files[0];
         //创建formdata对象
         var formdata = new FormData();
         formdata.append("file", file);
         //创建xhr,使用ajax进行文件上传
         var xhr = new XMLHttpRequest();
         xhr.open("post", "/attachment/upload");
         //回调
         xhr.onreadystatechange = function () {
             if (xhr.readyState == 4 && xhr.status == 200) {
                 document.querySelector("#callback").innerText = xhr.responseText;
             }
         }
         //获取上传的进度
         xhr.upload.onprogress = function (event) {
             if (event.lengthComputable) {
                 var percent = event.loaded / event.total * 100;
                 document.querySelector("#progress .progress-item").style.width = percent + "%";
             }
         }
         //将formdata上传
         xhr.send(formdata);
     }
 </script>

 </html>