1、vue前端
download(id) {
this.loadingShow=id
var fileName= "JAVA.rar"
// var fileName= "Downloads.zip"
Image.downloadImage({fileName: fileName,fileId: 11}).then(response => {
//createWebSocket(User.current().id);
console.log(response+'wwwwwwwwdwwwwwwwwwwwwwd')
})
// window.open(response.data.path);
var int = setInterval(function () {
Image.getLoadImageSum().then(response => {
console.log(JSON.stringify(response.data,null,4) , "--------------")
console.log(response.data.total + "--------------")
var total = response.data.total;
let processId='jindu'+id
var processJinDu= document.getElementById(processId)
console.log(processJinDu+'dddddddddddddddddd')
this.percent=total
processJinDu.innerHTML=total
processJinDu.style.width=total+'%'
processJinDu.setAttribute("aria-valuenow",total)
if (total == '100') {
//設置下載進度
// $('#proBar').css('width','100%');
//結束當前定時任務,
//clearInterval(int)方法的參數爲setInterval的變量名
//var int = setInterval...
clearInterval(int);
}
})
//100毫秒調用一次
}, 200);
},
2、java 後臺
package cn.shenzhou.cloud.controller;
import cn.shenzhou.admin.controller.base.BaseSpringController;
import cn.shenzhou.admin.entity.Image;
import cn.shenzhou.cloud.util.ProgressBarThread;
import com.alibaba.fastjson.JSONObject;
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.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
@Controller
public class DownloadController extends BaseSpringController {
//創建進度條
//必須要定義爲全局變量,這樣前臺才能訪問進度,且一個用戶一個進度
private ProgressBarThread pbt;
/**
* @author
* @date
* @Description: 獲取進度
* @param: @param request
* @param: @param response
* @return void
* @throws
*/
@RequestMapping("download/total")
public void text1(HttpServletRequest request , HttpServletResponse response){
//設置輸出文本格式
response.setContentType("application/json;charset=utf-8");
//獲取進度
String total = pbt.total();
//創建JSON
JSONObject json = new JSONObject();
//存儲進度
String path = request.getSession().
getServletContext().getRealPath("/download");
json.put("total", total);
json.put("downloadPath", path);
try {
//向前臺返回進度
response.getWriter().write(json.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @author
* @date
* @Description: 文件下載
* @param: @param fileName 文件名稱
* @return String 返回值爲null
* @throws
*/
@RequestMapping(value = "download/download", method = RequestMethod.POST)
public Object download( HttpServletRequest request,
HttpServletResponse response,@RequestParam Map<Object, Object> params) {
// User currentUser = getCurrentUser(request);
Image image =new Image();
response.setCharacterEncoding("utf-8");
String fileName=(String)params.get("fileName");
String fileId=(String)params.get("fileId");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
System.out.println(fileName+"-----------------------");
System.out.println(fileId+"-----------------------");
try {
// /WEB-INF/download文件夾的根目錄
String path = request.getSession().
getServletContext().getRealPath("/download");
// 獲取相應文件的流
// File.separator(Windows系統爲'/')
File file = new File(path + File.separator + fileName);
//創建進度條
pbt = new ProgressBarThread(file.length());
//開啓線程,刷新進度條
new Thread(pbt).start();
//設置文件長度
response.setHeader("Content-Length", file.length()+"");
//IO流複製
InputStream inputStream = new FileInputStream(file);
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
boolean bool;
while ((length = inputStream.read(b) )> 0) {
os.write(b, 0, length);
//寫完一次,更新進度條
bool= pbt.updateProgress(length);
System.out.println(bool +"---------------------------------");
if(bool ==false){
//文件讀取完成,關閉進度條
pbt.finish();
}
}
//Thread.sleep(2000);
// 釋放資源
os.close();
inputStream.close();
String filePath=path + File.separator + fileName;
image.setPath(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
}
----------------
package cn.shenzhou.cloud.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
public class ProgressBarThread implements Runnable{
private ArrayList<Integer> proList = new ArrayList<Integer>();
private int progress;//當前進度
private long totalSize;//總大小
private boolean run = true;
private java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");//格式化數字
//進度(百分比)
private String sum ;
private int addProcess ;
public ProgressBarThread(long totalSize){
this.totalSize = totalSize;
//創建進度條
System.out.println( this.totalSize+"==--------------------創建進度條------------");
}
//獲取總進度(百分比)
public String total(){
return sum;
}
/**
* @param progress 進度
*/
public boolean updateProgress(int progress){
boolean bool=true;
synchronized (this.proList) {
if(progress>0){
this.proList.add(progress);
this.proList.notify();
bool=true;
}else {
bool=false;
}
}
return bool;
}
public void finish(){
this.run = false;
//關閉進度條
}
@Override
public void run() {
synchronized (this.proList) {
try {
while (this.run) {
if(this.proList.size()==0){
this.proList.wait();
}
synchronized (proList) {
this.progress += this.proList.remove(0);
//更新進度條
System.out.println(this.totalSize+"====++++++++++++++++++++++++==========this.totalSize");
System.out.println(this.progress+"==============this.progress");
if( this.progress < this.totalSize) {
sum = df.format((int) (((float) this.progress / this.totalSize) * 100));
sum = sum.substring(0, sum.indexOf("."));
}else {
sum="100";
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ArrayList<Integer> proList = new ArrayList<Integer>();
try {
String path = "D:\\我的資料庫\\Downloads\\JAVA.rar";
//String path = "D:\\我的資料庫\\Downloads\\Downloads.zip";
File file = new File(path);
InputStream inputStream = new FileInputStream(file);
int length;
byte[] b = new byte[2048];
System.out.println(file.length());
while ((length = inputStream.read(b)) > 0) {
proList.add(length);
System.out.println(length +"__________________________________2_____________");
System.out.println(proList.remove(0) +"___________________3____________________________");
}
}catch (Exception e) {
e.printStackTrace();
}
}
}