spring boot large file upload implementations (a)

Controller
/**
* 上传文件
*
* @param param
* @param request
* @return
* @throws Exception
*/
@ApiOperation(value = "大文件上传")
@PostMapping(value = "/fileUpload")
@ResponseBody
public Result<String> fileUpload(MultipartFileParam param, HttpServletRequest request) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String parentId = request.getParameter("parentId");
if (isMultipart) {
logger.info("上传文件start。");
try {
personKnowledgeService.uploadFileByMappedByteBuffer(param,parentId);
} catch (IOException e) {
e.printStackTrace();
logger.error ( "failed files} {.", param.toString ());
return JsonError ( "Upload failed");
}
logger.info ( "upload files End.");
}
return JsonSuccess ( "successful upload" );
}



implementation


/ **
* Upload File Method 2
* file processing block, MappedByteBuffer achieved based save files
*
* @param param
* @throws IOException
* /
@Override
public void uploadFileByMappedByteBuffer(MultipartFileParam param, String parentId) throws IOException {

String basePath = System.getProperty("user.dir") + File.separator;
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String nowDayStr = sdf.format(now);
String filePath = "knowledge" + File.separator + "upload" + File.separator + nowDayStr + File.separator;

String fileName = param.getName();
String uploadDirPath = basePath + filePath + param.getUid();
String tempFileName = fileName + "_tmp";
File tmpDir = new File(uploadDirPath);
File tmpFile = new File(uploadDirPath, tempFileName);
if (!tmpDir.exists()) {
tmpDir.mkdirs();
}

//添加记录
long CHUNK_SIZE = 5242880;//5M
String uid = param.getUid();
PersonKnowledge model = personKnowledgeRepository.findFirstByFileuid(uid);
if (model == null) {
model = new PersonKnowledge();
model.setCreateTime(new Date());
model.setCreateId(SecurityUtils.getSubject().getCurrentUser().getId());
if (StringUtils.isEmpty(parentId)) {
parentId = "ROOT";
}
model.setParentId(parentId);
model.setAttchmentType(PersonKnowledgeType.文件.getId());
String suffixName = fileName.substring(fileName.lastIndexOf("."));
model.setName(fileName.substring(0, fileName.lastIndexOf("."))); // 新文件名
model.setAttachmentPath(uploadDirPath + File.separator + fileName); //文件路径
model.setSuffix(suffixName.toLowerCase().substring(1));
model.setFileuid(uid);
//获取文件大小
Long size = CHUNK_SIZE * param.getChunks();
String fileSizeString = "";
DecimalFormat df = new DecimalFormat("#.00");
if (size != null) {
if (size < 1024) {
fileSizeString = df.format((double) size) + "B";
model.setFileSize(fileSizeString);
} else if (size < 1048576) {
fileSizeString = df.format((double) size / 1024) + "K";
model.setFileSize(fileSizeString);
} else if (size < 1073741824) {
fileSizeString = df.format((double) size / 1048576) + "M";
model.setFileSize(fileSizeString);
} else {
fileSizeString = df.format((double) size / 1073741824) + "G";
model.setFileSize(fileSizeString);
}
}
personKnowledgeRepository.save(model);
}

RandomAccessFile tempRaf = new RandomAccessFile(tmpFile, "rw");
FileChannel fileChannel = tempRaf.getChannel();

//写入该分片数据

long offset = CHUNK_SIZE * param.getChunk();
byte[] fileData = param.getFile().getBytes();
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, offset, fileData.length);
mappedByteBuffer.put(fileData);
// 释放
FileMD5Util.freedMappedByteBuffer(mappedByteBuffer);
fileChannel.close();

boolean isOk = checkAndSetUploadProgress(param, uploadDirPath);
if (isOk) {
boolean flag = renameFile(tmpFile, fileName);
System.out.println("upload complete !!" + flag + " name=" + fileName);
}
}

/ ** 
* check and modify the file upload progress
*
* @param param
* @param uploadDirPath
* @return
* @throws IOException
* /
Private Boolean checkAndSetUploadProgress (param MultipartFileParam, String uploadDirPath) throws IOException {
String fileName = param.getName ();
File confFile = new new File (uploadDirPath, fileName + ".conf");
a RandomAccessFile accessConfFile a RandomAccessFile new new = (confFile, "RW");
// put the segment indicating completion flag is true
System.out.println ( "set part" param.getChunk + () + "Complete");
accessConfFile.setLength (param.getChunks ());
accessConfFile.seek (param.getChunk ());
accessConfFile.write (Byte.MAX_VALUE, whichever);

// Check if completeList completed, if in the array are all (the whole part of the film have been successfully uploaded)
byte [] completeList = FileUtils.readFileToByteArray (confFile);
byte = Byte.MAX_VALUE, whichever isComplete ;
for (int I = 0; I <== Byte.MAX_VALUE, whichever completeList.length && isComplete; I ++) {
// the operation, if there is no part of the completed isComplete not Byte.MAX_VALUE, whichever
isComplete = (byte) (isComplete & completeList [ I]);
System.out.println ( "Check Part" + I + "Complete ?:" completeList + [I]);
}

accessConfFile.close ();
IF (== Byte.MAX_VALUE, whichever isComplete) {
// stringRedisTemplate. opsForHash (). put (Constants.FILE_UPLOAD_STATUS, param.getMd5 (), "true");
//stringRedisTemplate.opsForValue().set(Constants.FILE_MD5_KEY + param.getMd5(), uploadDirPath + "/" + fileName);
return true;
} else {
// if (!stringRedisTemplate.opsForHash().hasKey(Constants.FILE_UPLOAD_STATUS, param.getMd5())) {
// stringRedisTemplate.opsForHash().put(Constants.FILE_UPLOAD_STATUS, param.getMd5(), "false");
// }
// if (stringRedisTemplate.hasKey(Constants.FILE_MD5_KEY + param.getMd5())) {
// stringRedisTemplate.opsForValue().set(Constants.FILE_MD5_KEY + param.getMd5(), uploadDirPath + "/" + fileName + ".conf");
// }
return false;
}
}

/**
* File renaming
*
* @param toBeRenamed going to change the name of the file
* @param toFileNewName new name
* @return
* /
public boolean RenameFile (File toBeRenamed, String toFileNewName) {
// check to rename the file exists, whether it is file
IF (! toBeRenamed.exists () || toBeRenamed.isDirectory ()) {
//logger.info("File does Not exist: "+ toBeRenamed.getName ());
return to false;
}
String toBeRenamed.getParent P = ( );
file file newFile new new = (P + + File.separatorChar toFileNewName);
// change the file name
return toBeRenamed.renameTo (newFile);
}

Guess you like

Origin www.cnblogs.com/gaozs/p/11514211.html