需求:
通過MultipartFile 上傳文件到文件服務器,上傳前要把文件轉為pdf格式進行上傳,并生成文件摘要用來驗證服務器中的文件是否被篡改。
準備:
需要涉及到 inputstream(輸入流)或outputStream(輸出流)要使用兩次 。
一、如果該文件本身就是pdf格式則直接進行上傳。第一次是通過輸入流去上傳文件;第二次是通過輸入流去生成文件摘要。
二、如果該文件不是pdf則需要工具類把文件轉為pdf再上傳。轉pdf的工具類 返回的為outputStream(輸出流)。上傳的工具類以及生成摘要的工具類則需要inputstream(輸入流)。
則需要把輸出流進行轉化變?yōu)檩斎肓鳎缓笤俚谝淮问峭ㄟ^輸入流去上傳文件;第二次是通過輸入流去生成文件摘要
注:流讀過一次就不能再讀了,而InputStream對象本身不能復制
文件、流之間的轉換
MultipartFile 轉 inputstream(輸入流)
byte [] byteArr=file.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);
outputStream(輸出流)轉為 inputstream(輸入流)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream inputStream2 = new ByteArrayInputStream(outputStream.toByteArray());
inputstream (輸入流)轉 ByteArrayOutputStream
//InputStream 轉 ByteArrayOutputStream
//獲取到一個inputstream后,可能要多次利用它進行read的操作。由于流讀過一次就不能再讀了,而InputStream對象本身不能復制,而且它也沒有實現(xiàn)Cloneable接口
public static ByteArrayOutputStream cloneInputStream(InputStream input) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
return baos;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
MultipartFile 文件直接轉輸入流上傳和生成摘要
通過file 轉字節(jié)數(shù)組,因為流不能重復讀,所以要new成兩個輸入流。文章來源:http://www.zghlxwxcb.cn/news/detail-619823.html
//獲取并生成以pdf為后綴的文件名稱
String fileName = StringUtils.substringBeforeLast(originalFilename,".");
fileName = fileName +".pdf";
//如果上傳的為pdf 則直接進行上傳 不需要轉換
if(originalFilename.endsWith(".pdf")){
//文件轉字節(jié)數(shù)組
byte [] byteArr=file.getBytes();
//輸入流1
InputStream inputStream = new ByteArrayInputStream(byteArr);
//輸入流2
InputStream inputStream2 = new ByteArrayInputStream(byteArr);
//文件上傳
url = CephUtils.uploadInputStreamReturnUrl("/" + Constants.CEPH_BUCK_NAME, fileName, inputStream);
//生成文檔hash 摘要
hash = FileHahUtil.hashAbstractByInputStream(inputStream2);
}
MultipartFile 文件需要轉為pdf 再進行上傳和生成摘要
//轉換為pdf 后的輸出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//原文件
byte [] byteArr=file.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);
//要轉為pdf 文檔
Word2PdfUtil.convert2PdfStream(inputStream,outputStream);
//輸出流轉輸入流
ByteArrayOutputStream baosPdf = (ByteArrayOutputStream) outputStream ;
InputStream inputStream2 = new ByteArrayInputStream(baosPdf.toByteArray());
//inputStream 只能用來讀取一次 所以進行copy一個新的 用來生成摘要
InputStream inputStream3 = new ByteArrayInputStream(baosPdf.toByteArray());
//生成文檔hash 摘要
hash = FileHahUtil.hashAbstractByInputStream(inputStream3);
//上傳文件
url = fileService.uploadFileByInputStream(inputStream2,fileName);
文件上傳源碼
//文件上傳(文檔轉pdf)
@ApiOperation(value = "文件上傳(文檔轉pdf)", produces = "application/json")
@ApiResponses(value = {@ApiResponse(code = 200, message = "文件上傳(文檔轉pdf)")})
@PostMapping(value = "/uploadWordFile")
public BaseVo<Contract> uploadWordFile(HttpServletRequest request, MultipartFile file, HttpServletResponse response){
long startTimeTotal = System.currentTimeMillis();
BaseVo<Contract> baseVo = new BaseVo<Contract>();
baseVo.setCodeMessage(CodeConstant.FAILURE_CODE);
try {
if(null != file){
String originalFilename = file.getOriginalFilename();
//文件上傳后返回的地址
String url = "";
//文件摘要的hash值
String hash = "";
if (!originalFilename.endsWith(".docx") && !originalFilename.endsWith(".doc") && !originalFilename.endsWith(".pdf")) {
//上傳的文件格式不支持
baseVo.setMessage("暫不支持當前文件格式上傳!");
}else {
//生成新的文件名稱
String fileName = StringUtils.substringBeforeLast(originalFilename,".");
fileName = fileName +".pdf";
//如果上傳的為pdf 則直接進行上傳 不需要轉換
if(originalFilename.endsWith(".pdf")){
byte [] byteArr=file.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);
InputStream inputStream2 = new ByteArrayInputStream(byteArr);
url = CephUtils.uploadInputStreamReturnUrl("/" + Constants.CEPH_BUCK_NAME, fileName, inputStream);
//生成文檔hash 摘要
hash = FileHahUtil.hashAbstractByInputStream(inputStream2);
}else {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte [] byteArr=file.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);
//要轉為pdf 文檔
Word2PdfUtil.convert2PdfStream(inputStream,outputStream);
ByteArrayOutputStream baosPdf = (ByteArrayOutputStream) outputStream ;
InputStream inputStream2 = new ByteArrayInputStream(baosPdf.toByteArray());
//inputStream 只能用來讀取一次 所以進行copy一個新的 用來生成摘要
InputStream inputStream3 = new ByteArrayInputStream(baosPdf.toByteArray());
//生成文檔hash 摘要
hash = FileHahUtil.hashAbstractByInputStream(inputStream3);
url = fileService.uploadFileByInputStream(inputStream2,fileName);
baosPdf.close();
inputStream2.close();
outputStream.close();
}
if(StringUtils.isNotEmpty(url)){
// 保存合同信息 到數(shù)據(jù)庫
Contract contract = new Contract();
//隨機字符串
String str = StringUtils.replace(UUID.randomUUID().toString(), "-", "");
contract.setCode(CodeGenerator.getLongCode(str));
contract.setContractUrl(url);
contract.setName(fileName);
contract.setHashCode(hash);
contractService.saveOrUpdate(contract);
//返回合同信息
baseVo.setData(contract);
baseVo.setCodeMessage(CodeConstant.SUCCESS_CODE);
}
}
}
}catch (Exception e){
e.printStackTrace();
MeUtils.info("uploadFile error",e);
}
long endTimeTotal = System.currentTimeMillis();
MeUtils.info("uploadFile total time:" + (endTimeTotal - startTimeTotal));
return baseVo;
}
生成文件摘要用的是文件hash 摘要算法中的SHA-256,docx或doc轉pdf用的是aspose 中提供的方法,文件上傳用的Ceph分布式文件系統(tǒng)中的。這里暫時不詳細介紹,只貼一些代碼。后面再出詳細文檔,以及開發(fā)中遇到的坑。文章來源地址http://www.zghlxwxcb.cn/news/detail-619823.html
文件hash 摘要算法
/**
* 生成文件hashCode值
*/
public static String hashAbstractByInputStream(InputStream fis) throws Exception {
String sha256 = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte buffer[] = new byte[1024];
int length = -1;
while ((length = fis.read(buffer, 0, 1024)) != -1) {
md.update(buffer, 0, length);
}
byte[] digest = md.digest();
sha256 = byte2hexLower(digest);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("生成文件hash值失敗");
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sha256;
}
docx或doc轉pdf
public static void convert2PdfStream(InputStream inputStream, ByteArrayOutputStream outputStream) {
if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文檔會有水印產(chǎn)生
return;
}
try {
long old = System.currentTimeMillis();
Document doc = new Document(inputStream);
//insertWatermarkText(doc, "測試水印"); //添加水印
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setSaveFormat(SaveFormat.PDF);
// 設置3級doc書簽需要保存到pdf的heading中
pdfSaveOptions.getOutlineOptions().setHeadingsOutlineLevels(3);
// 設置pdf中默認展開1級
pdfSaveOptions.getOutlineOptions().setExpandedOutlineLevels(1);
//doc.save(outputStream, pdfSaveOptions);
// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,EPUB, XPS, SWF 相互轉換
doc.save(outputStream, SaveFormat.PDF);
long now = System.currentTimeMillis();
System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒"); // 轉化用時
} catch (Exception e) {
e.printStackTrace();
}
}
文件上傳
/**
* 上傳InputStream文件
*
* @param bucketName
* @param fileName
* @param input
*/
public static String uploadInputStreamReturnUrl(String bucketName, String fileName, InputStream input) {
// String path = bucketName + timeSuffix();
PutObjectResult putObjectResult = conn.putObject(bucketName, fileName, input, new ObjectMetadata());
String cephUrl = ENDPOINT + bucketName + "/" + fileName;
return cephUrl;
}
到了這里,關于outputStream(輸出流)轉inputstream(輸入流)以及輸入流如何復用的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!