Java
WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。

大文件上传

实现思路

分片: 按照自定义缓冲区大小,将大文件分成多个小文件片段。
断点续传: 根据分片数量,给每个小文件通过循环起对应名称,当文件下载中断在续传时,判断小文件名称若存在则不存了,此时还需要判断文件若不是最后一个分片则大小为缓冲区固定大小,若没达到则证明小文件没传完需要重新传输。
合并: 下载时通过线程池创建任务进行下载或上传、当判断最后一个分片传完时,调用合并方法,根据之前定义的文件名称顺序进行合并,肯能出现最后一个分片传完,之前分片未传完的情况,需要使用while循环进行判断,多文件未传输完,则等待一会继续判断。
大文件秒传: 实际上是根据文件名称区一个唯一的md5值存储,传文件时进行判断,若存在则不传。
创建SpringBoot项目,添加依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-test</artifactId>
  9. <scope>test</scope>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-autoconfigure</artifactId>
  14. </dependency>
  15. <dependency>
  16. <groupId>commons-fileupload</groupId>
  17. <artifactId>commons-fileupload</artifactId>
  18. <version>1.3.1</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>commons-io</groupId>
  22. <artifactId>commons-io</artifactId>
  23. <version>2.4</version>
  24. </dependency>
  25. <!-- 做断点下载使用-->
  26. <dependency>
  27. <groupId>org.apache.httpcomponents</groupId>
  28. <artifactId>httpcore</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.apache.httpcomponents</groupId>
  32. <artifactId>httpclient</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-web</artifactId>
  37. </dependency>
  38. </dependencies>

编写测试环境看环境有没有搭建成功

  1. @Controller
  2. public class UploadController {
  3. @RequestMapping("/up")
  4. @ResponseBody
  5. public String upload(HttpServletRequest request, HttpServletResponse response){
  6. return "搭建成功";
  7. }
  8. }

页面主要代码

  1. <body>
  2. <div id="upload-container">
  3. <span>上传</span>
  4. </div>
  5. <div id="upload-list"></div>
  6. <button id="picker">点击上传</button>
  7. </body>
  8. <script>
  9. $('#upload-container').click(function (event){
  10. $("#picker").find('input').click();
  11. });
  12. var uploader = WebUploader.create({
  13. auto: true,
  14. swf : 'Uploader.swf', //swf文件路径
  15. server: 'http://localhost:8080/upload',
  16. dnd: '#upload-container',
  17. pick: '#picker', //内部根据当前运行创建
  18. multiple: true, //选择多个
  19. chunked: true, //开启分片
  20. threads: 20, //并发数
  21. method: 'POST',
  22. fileSizeLimit: 1024*1024*1024*10, //单个文件大小限制
  23. fileSingleSizeLimit: 1024*1024*1024, //总文件大小
  24. fileVal: 'upload'
  25. });
  26. uploader.on("beforeFileQueued",function (file){
  27. console.log(file); //获取文件后缀
  28. });
  29. uploader.on('fileQueued',function (file){
  30. //选中文件要做的事
  31. console.log(file.ext);
  32. console.log(file.size);
  33. console.log(file.name);
  34. var html = '<div class="upload-item"><span>文件名:'+file.name+'</span><span data-file_id="'+file.id+'"class="btn-delete">删除</span><span data-file_id="'+file.id+'"class="btn-retry">重试</span><div class="percentage '+file.id+'" style="width: 0%;"></div></div>'
  35. $('#upload-list').append(html);
  36. uploader.md5File(file) //给文件定义唯一的md5值,当再次上传相同文件时,就不用传了 大文件秒传实际上是没传,直接拷贝之前文件地址
  37. //显示进度
  38. .progress(function (percentage){
  39. console.log('Percentage:',percentage);
  40. })
  41. //完成
  42. .then(function (val){
  43. console.log('md5 result',val);
  44. });
  45. });
  46. </script>

webUpload组件支持分片上传:利用多进程并发上传,将大文件拆分成一个一个的小文件,每一个小文件属于大文件的一个分片

断点续传实现:后端代码

  1. @Controller
  2. public class UploadController {
  3. private final static String utf8 = "utf-8";
  4. @RequestMapping("/up")
  5. @ResponseBody
  6. public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
  7. response.setCharacterEncoding(utf8);
  8. //长传时候会有多个分片,需要记录当前为那个分片
  9. Integer schunk = null;
  10. //总分片数
  11. Integer schunks = null;
  12. //名字
  13. String name = null;
  14. //文件目录
  15. String path = "D:\\file";
  16. BufferedOutputStream os = null;
  17. try {
  18. //设置缓冲区大小 先读到内存里在从内存写
  19. DiskFileItemFactory factory = new DiskFileItemFactory();
  20. factory.setSizeThreshold(1024);
  21. factory.setRepository(new File(path));
  22. //解析
  23. ServletFileUpload upload = new ServletFileUpload(factory);
  24. //设置单个大小与最大大小
  25. upload.setFileSizeMax(5l*1024l*1024l*1024l);
  26. upload.setSizeMax(10l*1024l*1024l*1024l);
  27. List<FileItem> items = upload.parseRequest(request);
  28. for (FileItem item : items){
  29. if (item.isFormField()){
  30. //获取分片数赋值给遍量
  31. if ("chunk".equals(item.getFieldName())){
  32. schunk = Integer.parseInt(item.getString(utf8));
  33. }
  34. if ("chunks".equals(item.getFieldName())){
  35. schunks = Integer.parseInt(item.getString(utf8));
  36. }
  37. if ("name".equals(item.getFieldName())){
  38. name = item.getString(utf8);
  39. }
  40. }
  41. }
  42. //取出文件基本信息后
  43. for (FileItem item : items){
  44. if (!item.isFormField()){
  45. //有分片需要临时目录
  46. String temFileName = name;
  47. if (name != null){
  48. if (schunk != null){
  49. temFileName = schunk+"_"+name;
  50. }
  51. //判断文件是否存在
  52. File temfile = new File(path, temFileName);
  53. //断点续传 判断文件是否存在,若存在则不传
  54. if (!temfile.exists()){
  55. item.write(temfile);
  56. }
  57. }
  58. }
  59. }
  60. //文件合并 当前分片为最后一个就合并
  61. if (schunk != null && schunk.intValue()== schunks.intValue()-1){
  62. File tempFile = new File(path, name);
  63. os = new BufferedOutputStream(new FileOutputStream(tempFile));
  64. //根据之前命名规则找到所有分片
  65. for (int i = 0; i < schunks; i++) {
  66. File file = new File(path, i + "_" + name);
  67. //并发情况 需要判断所有 因为可能最后一个分片传完,之前有的还没传完
  68. while (!file.exists()){
  69. //不存在休眠100毫秒后在从新判断
  70. Thread.sleep(100);
  71. }
  72. //分片存在 读入数组中
  73. byte[] bytes = FileUtils.readFileToByteArray(file);
  74. os.write(bytes);
  75. os.flush();
  76. file.delete();
  77. }
  78. os.flush();
  79. }
  80. response.getWriter().write("上传成功");
  81. }finally {
  82. try {
  83. if (os != null){
  84. os.close();
  85. }
  86. }catch (IOException e){
  87. e.printStackTrace();
  88. }
  89. }
  90. }
  91. }

文件分片下载服务端

  1. @Controller
  2. public class DownLoadController {
  3. private final static String utf8 = "utf-8";
  4. @RequestMapping("/down")
  5. public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
  6. response.setCharacterEncoding(utf8);
  7. //定义文件路径
  8. File file = new File("D:\\File\\a.mp4");
  9. InputStream is = null;
  10. OutputStream os = null;
  11. try {
  12. //分片下载
  13. long fSize = file.length();//获取长度
  14. response.setContentType("application/x-download");
  15. String fileName = URLEncoder.encode(file.getName(),utf8);
  16. response.addHeader("Content-Disposition","attachment;filename="+fileName);
  17. //根据前端传来的Range 判断支不支持分片下载
  18. response.setHeader("Accept-Range","bytes");
  19. //获取文件大小
  20. response.setHeader("fSize",String.valueOf(fSize));
  21. response.setHeader("fName",fileName);
  22. //定义断点
  23. long pos = 0,last = fSize-1,sum = 0;
  24. //判断前端需不需要分片下载
  25. if (null != request.getHeader("Range")){
  26. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
  27. String numRange = request.getHeader("Range").replaceAll("bytes=","");
  28. String[] strRange = numRange.split("-");
  29. if (strRange.length == 2){
  30. pos = Long.parseLong(strRange[0].trim());
  31. last = Long.parseLong(strRange[1].trim());
  32. //若结束字节超出文件大小 取文件大小
  33. if (last>fSize-1){
  34. last = fSize-1;
  35. }
  36. }else {
  37. //若只给一个长度 开始位置一直到结束
  38. pos = Long.parseLong(numRange.replaceAll("-","").trim());
  39. }
  40. }
  41. long rangeLenght = last-pos+1;
  42. String contentRange = new StringBuffer("bytes").append(pos).append("-").append(last).append("/").append(fSize).toString();
  43. response.setHeader("Content-Range",contentRange);
  44. response.setHeader("Content-Lenght",String.valueOf(rangeLenght));
  45. os = new BufferedOutputStream(response.getOutputStream());
  46. is = new BufferedInputStream(new FileInputStream(file));
  47. is.skip(pos);//跳过已读的文件
  48. byte[] buffer = new byte[1024];
  49. int lenght = 0;
  50. //相等证明读完
  51. while (sum < rangeLenght){
  52. lenght = is.read(buffer,0, (rangeLenght-sum)<=buffer.length? (int) (rangeLenght - sum) :buffer.length);
  53. sum = sum+lenght;
  54. os.write(buffer,0,lenght);
  55. }
  56. System.out.println("下载完成");
  57. }finally {
  58. if (is!= null){
  59. is.close();
  60. }
  61. if (os!=null){
  62. os.close();
  63. }
  64. }
  65. }
  66. }

客户端分片下载,指定固定文件

  1. @RestController
  2. public class DownloadClient {
  3. private final static long per_page = 1024l*1024l*50l;
  4. //分片存储临时目录 当分片下载完后在目录中找到文件合并
  5. private final static String down_path="D:\\File";
  6. //多线程下载
  7. ExecutorService pool = Executors.newFixedThreadPool(10);
  8. //文件大小 分片数量 文件名称
  9. //使用探测 获取变量
  10. //使用多线程分片下载
  11. //最后一个分片下载完 开始合并
  12. @RequestMapping("/downloadFile")
  13. public String downloadFile() throws IOException {
  14. FileInfo fileInfo = download(0,10,-1,null);
  15. if (fileInfo!= null){
  16. long pages = fileInfo.fSize/per_page;
  17. for (int i = 0; i <= pages; i++) {
  18. pool.submit(new Download(i*per_page,(i+1)*per_page-1,i,fileInfo.fName));
  19. }
  20. }
  21. return "成功";
  22. }
  23. class Download implements Runnable{
  24. long start;
  25. long end;
  26. long page;
  27. String fName;
  28. public Download(long start, long end, long page, String fName) {
  29. this.start = start;
  30. this.end = end;
  31. this.page = page;
  32. this.fName = fName;
  33. }
  34. @Override
  35. public void run() {
  36. try {
  37. FileInfo fileInfo = download(start,end,page,fName);
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43. //返回文件名 跟大小
  44. private FileInfo download(long start,long end,long page,String fName) throws IOException {
  45. //断点下载 文件存在不需要下载
  46. File file = new File(down_path, page + "-" + fName);
  47. //探测必须放行 若下载分片只下载一半就锻炼需要重新下载所以需要判断文件是否完整
  48. if (file.exists()&&page != -1&&file.length()==per_page){
  49. return null;
  50. }
  51. //需要知道 开始-结束 = 分片大小
  52. HttpClient client = HttpClients.createDefault();
  53. //httpclient进行请求
  54. HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/down");
  55. //告诉服务端做分片下载
  56. httpGet.setHeader("Range","bytes="+start+"-"+end);
  57. HttpResponse response = client.execute(httpGet);
  58. String fSize = response.getFirstHeader("fSize").getValue();
  59. fName= URLDecoder.decode(response.getFirstHeader("fName").getValue(),"utf-8");
  60. HttpEntity entity = response.getEntity();//获取文件流对象
  61. InputStream is = entity.getContent();
  62. //临时存储分片文件
  63. FileOutputStream fos = new FileOutputStream(file);
  64. byte[] buffer = new byte[1024];//定义缓冲区
  65. int ch;
  66. while ((ch = is.read(buffer)) != -1){
  67. fos.write(buffer,0,ch);
  68. }
  69. is.close();
  70. fos.flush();
  71. fos.close();
  72. //判断是不是最后一个分片
  73. if (end-Long.valueOf(fSize)>0){
  74. //合并
  75. try {
  76. mergeFile(fName,page);
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. }
  80. }
  81. return new FileInfo(Long.valueOf(fSize),fName);
  82. }
  83. private void mergeFile(String fName, long page) throws Exception {
  84. //归并文件位置
  85. File file = new File(down_path, fName);
  86. BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
  87. for (int i = 0; i <= page; i++) {
  88. File tempFile = new File(down_path, i + "-" + fName);
  89. //分片没下载或者没下载完需要等待
  90. while (!file.exists()||(i!=page&&tempFile.length()<per_page)){
  91. Thread.sleep(100);
  92. }
  93. byte[] bytes = FileUtils.readFileToByteArray(tempFile);
  94. os.write(bytes);
  95. os.flush();
  96. tempFile.delete();
  97. }
  98. File file1 = new File(down_path, -1 + "-null");
  99. file1.delete();
  100. os.flush();
  101. os.close();
  102. }
  103. //使用内部类实现
  104. class FileInfo{
  105. long fSize;
  106. String fName;
  107. public FileInfo(long fSize, String fName) {
  108. this.fSize = fSize;
  109. this.fName = fName;
  110. }
  111. }
  112. }