您好,登錄后才能下訂單哦!
項目地址:
https://download.csdn.net/download/zxcnlmx/10389632
功能描述
1、webuploader是百度研發的上傳組件,文檔不是特別規整,但是也夠用了。
2、前端使用官網的上傳圖片demo,在此基礎上代碼略微調整做分片。既可以上傳圖片也可以上傳文件。文件超過分片大小才啟用分片。
3、分片上傳已做md5校驗,達到秒傳的效果。分片以后需要合并,可以先分片后合并,也可以邊分片邊合并,本示例采用的是邊分片邊合并的方案。
4、后端用springboot做框架搭建。springMVC做rest服務,開啟跨域訪問。
5、容器用springboot內置的tomcat插件,運行Application的main方法即可啟動服務;
顯示效果
關鍵代碼
前端
WebUploader.Uploader.register({
'name': 'webUploaderHookCommand',
'before-send-file': 'beforeSendFile',
"before-send": "beforeSend"
}, {
beforeSendFile: function(file) {
var task = new WebUploader.Deferred();
fileName = file.name;
fileSize = file.size;
(new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024).progress(function(percentage) {}).then(function(val) {
fileMd5 = val;
var url = checkUrl;
var data = {
type: 0,
fileName: fileName,
fileMd5: fileMd5,
fileSize: fileSize
};
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
async: false, // 同步
timeout: 1000, // todo 超時的話,只能認為該分片未上傳過
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown) {
file.statusText = 'server_error';
task.reject();
}
}).then(function(data, textStatus, jqXHR) {
if(data.rtn == 0) {
if(data.obj == 1) {
file.statusText = 'file_existed';
task.reject();
} else {
task.resolve();
}
} else {
task.reject();
}
});
});
return task.promise();
},
beforeSend: function(block) {
var task = new WebUploader.Deferred();
var url = checkUrl;
var data = {
type: 1,
fileName: fileName,
fileMd5: fileMd5,
chunk: block.chunk,
fileSize: block.end - block.start
};
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
async: false, // 同步
timeout: 1000, // todo 超時的話,只能認為該分片未上傳過
dataType: "json"
}).then(function(data, textStatus, jqXHR) {
if(data.rtn == 0 && data.obj == 1) {
task.reject(); // 分片存在,則跳過上傳
} else {
task.resolve();
}
});
this.owner.options.formData.fileMd5 = fileMd5;
this.owner.options.formData.chunkSize = chunkSize;
return task.promise();
}
});
// 實例化
uploader = WebUploader.create({
pick: {
id: '#filePicker',
label: '點擊選擇文件'
},
formData: {
uid: 123
},
dnd: '#dndArea', //指定文件拖拽的區域
paste: '#uploader', //指定監聽paste事件的容器,如果不指定,不啟用此功能。此功能為通過粘貼來添加截屏的圖片。建議設置為document.body.
swf: '../plugins/webuploader/Uploader.swf',
chunked: true,
chunkSize: chunkSize,
chunkRetry: false,
threads: 1,
server: uploadUrl,
// runtimeOrder: 'flash',
// accept: {
// title: 'Images',
// extensions: 'gif,jpg,jpeg,bmp,png',
// mimeTypes: 'image/*'
// },
// 禁掉全局的拖拽功能。這樣不會出現圖片拖進頁面的時候,把圖片打開。
disableGlobalDnd: true,
fileNumLimit: 300 //限制多文件上傳的個數
//fileSizeLimit: 200 * 1024 * 1024, // 限制所有文件的大小 200 M
//fileSingleSizeLimit: 50 * 1024 * 1024 // 限制單個文件的大小 50 M
});
后端
import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.bear.upload.util.FileUtil;
import com.bear.upload.util.RETURN;
import com.bear.upload.vo.CheckMd5FileVO;
import com.bear.upload.vo.UploadVO;
@Service
public class ChunkUploadService {
private static Logger LOG = LoggerFactory.getLogger(ChunkUploadService.class);
@Value("${file.upload.path}")
private String UPLOAD_PATH;
private static final String Delimiter = "-";
/**
* 上傳之前校驗(整個文件、分片)
*
* @param md5FileVO
* @return
*/
public Object check(CheckMd5FileVO md5FileVO) {
Integer type = md5FileVO.getType();
Long chunk = md5FileVO.getChunk();
String fileName = md5FileVO.getFileName();
Long fileSize = md5FileVO.getFileSize();
if (type == 0) {// 未分片校驗
String destfilePath = UPLOAD_PATH + File.separator + fileName;
File destFile = new File(destfilePath);
if (destFile.exists() && destFile.length() == fileSize) {
return RETURN.success("文件已存在,跳過", 1);
} else {
return RETURN.success("文件不存在", 0);
}
} else {// 分片校驗
String fileMd5 = md5FileVO.getFileMd5();
String destFileDir = UPLOAD_PATH + File.separator + fileMd5;
String destFileName = chunk + Delimiter + fileName;
String destFilePath = destFileDir + File.separator + destFileName;
File destFile = new File(destFilePath);
if (destFile.exists() && destFile.length() == fileSize) {
return RETURN.success("分片已存在,跳過", 1);
} else {
return RETURN.success("分片不存在", 0);
}
}
}
/**
* 文件上傳
*
* @param file
* @param uploadVO
* @param appVersion
* @return
*/
public Object upload(MultipartFile file, UploadVO uploadVO) {
Long chunk = uploadVO.getChunk();
if (chunk == null) {// 沒有分片
return UnChunkUpload(file, uploadVO);
} else {// 分片
return ChunkUpload(file, uploadVO);
}
}
/**
* 分片上傳
*
* @param file
* @param uploadVO
* @param appVersion
* @return
*/
public Object ChunkUpload(MultipartFile file, UploadVO uploadVO) {
String fileName = uploadVO.getName();
String fileMd5 = uploadVO.getFileMd5();
Long chunk = uploadVO.getChunk();// 當前片
Long chunks = uploadVO.getChunks();// 總共多少片
// 分片目錄創建
String chunkDirPath = UPLOAD_PATH + File.separator + fileMd5;
File chunkDir = new File(chunkDirPath);
if (!chunkDir.exists()) {
chunkDir.mkdirs();
}
// 分片文件上傳
String chunkFileName = chunk + Delimiter + fileName;
String chunkFilePath = chunkDir + File.separator + chunkFileName;
File chunkFile = new File(chunkFilePath);
try {
file.transferTo(chunkFile);
} catch (Exception e) {
LOG.error("分片上傳出錯", e);
return RETURN.fail("分片上傳出錯", 1);
}
// 合并分片
Long chunkSize = uploadVO.getChunkSize();
long seek = chunkSize * chunk;
String destFilePath = UPLOAD_PATH + File.separator + fileName;
File destFile = new File(destFilePath);
if (chunkFile.length() > 0) {
try {
FileUtil.randomAccessFile(chunkFile, destFile, seek);
} catch (IOException e) {
LOG.error("分片{}合并失敗:{}", chunkFile.getName(), e.getMessage());
return RETURN.fail("分片合并失敗", 1);
}
}
if (chunk == chunks - 1) {
// 刪除分片文件夾
FileUtil.deleteDirectory(chunkDirPath);
return RETURN.success("上傳成功", 1);
} else {
return RETURN.fail("上傳中...", 1);
}
}
/**
* 未分片上傳
*
* @param file
* @param uploadVO
* @param appVersion
* @return
*/
public Object UnChunkUpload(MultipartFile file, UploadVO uploadVO) {
String fileName = uploadVO.getName();
// String fileMd5 = uploadVO.getFileMd5();
// 文件上傳
File destFile = new File(UPLOAD_PATH + File.separator + fileName);
if (file != null && !file.isEmpty()) {
// 上傳目錄
File fileDir = new File(UPLOAD_PATH);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
if (destFile.exists()) {
destFile.delete();
}
try {
file.transferTo(destFile);
return RETURN.success("上傳成功", 0);
} catch (Exception e) {
LOG.error("文件上傳出錯", e);
return RETURN.fail("文件上傳出錯", 0);
}
}
return RETURN.fail("上傳失敗", 0);
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。