大文件文件分片上传
/**
* 前端可以参考百度的分片
* 大文件分片上传
* @param file 单次分片上传文件
* @param chunk 当前分片数 起始值为0
* @param totalChunkNumbers 文件总分片数
* @param chunkSize 文件每片大小
*/
public void chunkRandomAccessFile(File file, String fileName, int chunk, int totalChunkNumbers, int chunkSize ) {
FileOutputStream tempFile = null;
int donat = fileName.lastIndexOf(".");
String subStringFile = fileName.substring(0, donat);
try {
FileInputStream source = new FileInputStream(file);
String uploadPath = FILE_UPLOAD_TMP_PATH + "\\" + subStringFile + "tmp";
File directory = new File(uploadPath);
if (!directory.exists()) {
directory.mkdirs(); // 创建路径
}
File uploadFile = new File(directory, subStringFile + "_" + chunk + ".tmp");
tempFile = new FileOutputStream(uploadFile);
byte[] bytes = source.readAllBytes();
int length = bytes.length;
//数据校验 前后台分片大小校验
if (chunkSize != length || CHUNK_SIZE != chunkSize) {
log.debug("分片非法!");
return;
}
tempFile.write(bytes, 0, length);
tempFile.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (tempFile != null) {
try {
tempFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//合并文件
if (chunk > 0 && totalChunkNumbers == chunk) {
BufferedOutputStream bufferedOutputStream;
try {
File finalFile = new File(FILE_UPLOAD_TMP_PATH + "\\" + fileName);
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(finalFile));
int index = 0;
for (int i = 0; i < totalChunkNumbers; i++) {
index++;
File tempFileSecond = new File(FILE_UPLOAD_TMP_PATH, subStringFile + "tmp\\" + subStringFile + "_" + index + ".tmp");
while (!tempFileSecond.exists()) {//断点续传
//并发情况下最后一个分片不一定先到 等一会
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
FileInputStream fileInputStream = new FileInputStream(tempFileSecond);
byte[] tempByte = fileInputStream.readAllBytes();
bufferedOutputStream.write(tempByte);
fileInputStream.close();
//多次删除小文件会增加磁盘的负载和时间的消耗
// tempFileSecond.delete();
bufferedOutputStream.flush();
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
File tempFolder = new File(FILE_UPLOAD_TMP_PATH, subStringFile + "tmp");
deleteFolder(tempFolder);
}
}
public void deleteFolder(File folder) {
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
deleteFolder(file);
}
}
}
folder.delete();
}
private static final String FILE_PATH = "D:\\qqq\\1111.docx";
private static final String FILE_UPLOAD_TMP_PATH = "D:\\qqq";
private static final int CHUNK_SIZE = 14670;
本文来自博客园,作者:余生请多指教ANT,转载请注明原文链接:https://www.cnblogs.com/wangbiaohistory/p/16950704.html

浙公网安备 33010602011771号