WebUploader小案例之文件分块上传和断点续传之后台实现,如果不好之处请大家多多指教

package org.mini.webupload;
/*
分块上传和断点上传
*/
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@javax.servlet.annotation.WebServlet(“/webUploadServlet”)
public class ServletWebServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request,response);
}

protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);
    /*List item = null;
    try {
       item = sfu.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    for(FileItem iter : item){
        if(iter.isFormField()) {
            //普通信息
        }else{
            //文件信息  判断只有文件才需要进行保存处理
            String name = iter.getName();
            name = new String(name.getBytes("ISO-8859-1"),"utf-8");
            System.out.println("接受的文件名称:"+name);
            //拷贝文件到后台硬盘
            FileUtils.copyInputStreamToFile(iter.getInputStream(),new File("d:/a/"+iter.getName()));
            System.out.println("文件保存成功");
        }
    }

*/
/*
分块上传和断点上传
*/
//防止文件中文乱码
sfu.setHeaderEncoding(“utf-8”);
//保存路径
String savePath = “d://a”;
String foload = “uploads”;
savePath = savePath +”\”+foload+”\”;
//采用MD5
String fileMd5 = null;
String chunk = null;

    try {
        List items = sfu.parseRequest(request);

        for(FileItem item:items){
            if(item.isFormField()){
                String fieldName = item.getFieldName();
                if(fieldName.equals("fileMd5")){
                    fileMd5 = item.getString("utf-8");
                }
                if(fieldName.equals("chunk")){
                    chunk = item.getString("utf-8");
                }
            }else{
                File file = new File(savePath+"/"+fileMd5);
                if(!file.exists()){
                    file.mkdir();
                }
                File chunkFile = new File(savePath+"/"+fileMd5+"/"+chunk);
                FileUtils.copyInputStreamToFile(item.getInputStream(), chunkFile);

            }
        }

    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}

package org.mini.webupload;
/*
实现断点上传的文件的合并
*/
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.*;

@WebServlet(“/video”)
public class ServletSequence extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String savePath = "d://a";
    String folad = "uploads";
    savePath = savePath + "\\"+folad+"\\";

    String action = request.getParameter("action");

    if(action.equals("mergeChunks")){
        //合并文件
        //需要合并的文件的目录标记
        String fileMd5 = request.getParameter("fileMd5");

        //读取目录里的所有文件
        File f = new File(savePath+"/"+fileMd5);
        File[] fileArray = f.listFiles(new FileFilter(){
            //排除目录只要文件
            @Override
            public boolean accept(File pathname) {
                // TODO Auto-generated method stub
                if(pathname.isDirectory()){
                    return false;
                }
                return true;
            }
        });

        //转成集合,便于排序
        List fileList = new ArrayList(Arrays.asList(fileArray));
        Collections.sort(fileList,new Comparator() {
            @Override
            public int compare(File o1, File o2) {
                // TODO Auto-generated method stub
                if(Integer.parseInt(o1.getName()) < Integer.parseInt(o2.getName())){
                    return -1;
                }
                return 1;
            }
        });
        //UUID.randomUUID().toString()-->随机名
        File outputFile = new File(savePath+"/"+fileMd5+".mp4");
        //创建文件
        outputFile.createNewFile();
        //输出流
        FileChannel outChnnel = new FileOutputStream(outputFile).getChannel();
        //合并
        FileChannel inChannel;
        for(File file : fileList){
            inChannel = new FileInputStream(file).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChnnel);
            inChannel.close();
            //删除分片
            file.delete();
        }
        outChnnel.close();
        //清除文件夹
        File tempFile = new File(savePath+"/"+fileMd5);
        if(tempFile.isDirectory() && tempFile.exists()){
            tempFile.delete();
        }
        System.out.println("合并成功");
    }else if(action.equals("checkChunk")){
        //检查当前分块是否上传成功
        String fileMd5 = request.getParameter("fileMd5");
        String chunk = request.getParameter("chunk");
        String chunkSize = request.getParameter("chunkSize");

        File checkFile = new File(savePath+"/"+fileMd5+"/"+chunk);

        response.setContentType("text/html;charset=utf-8");
        //检查文件是否存在,且大小是否一致
        if(checkFile.exists() && checkFile.length()==Integer.parseInt(chunkSize)){
            //上传过
            response.getWriter().write("{\"ifExist\":1}");
        }else{
            //没有上传过
            response.getWriter().write("{\"ifExist\":0}");
        }
    }
}
}

你可能感兴趣的:(IDEA)