能够帮到你们的话,就给我留个言,给我一点信心记录更多有用的东西
成品页面
pom.xml
<!--Fastdfs 分布式文件系统
FDFS-->
<dependency
>
<groupId
>com
.github
.tobato
</groupId
>
<artifactId
>fastdfs
-client
</artifactId
>
<version
>1.26.1-RELEASE</version
>
</dependency
>
<!--excel工具
-->
<dependency
>
<groupId
>org
.apache
.poi
</groupId
>
<artifactId
>poi
</artifactId
>
<version
>4.0.1</version
>
</dependency
>
<dependency
>
<groupId
>org
.apache
.poi
</groupId
>
<artifactId
>poi
-ooxml
</artifactId
>
<version
>4.0.1</version
>
</dependency
>
html页面
<!--附件上传
-->
<div
class="layui-tab-item">
<div
class="layui-row">
<form
class="layui-form layui-col-md12 x-so">
<div
class="layui-input-inline">
<input type
="text" value
="" id
="fileName" placeholder
="附件名称" class="layui-input">
</div
>
<a
class="layui-btn search_btn"><i
class="layui-icon">
;</i
></a
>
<button type
="button" class="layui-btn layui-btn-sm" id
="fileUpload"><i
class="layui-icon">
</i
>上传文件
</button
>
</form
>
</div
>
<table
class="layui-table" id
="hjTable" lay
-filter
="hjFilter"></table
>
<div
class="page" id
="pageDiv"></div
>
</div
>
<!-- 工具栏模板
-->
<div
class="tool_template" type
="text/html" id
="toolBar">
<a
class="layui-btn layui-btn-xs layui-btn-normal" lay
-event
="download">下载
</a
>
</div
>
js
var busId
= parent
.pkId
;
fileTableIns
= table
.render({
cols
: [[
{type
: 'numbers', title
: '序号', fixed
: 'left'},
{
field
: 'fileName',
title
: '附件名称',
align
: 'center',
minWidth
: 180,
templet
: '<div>{{d.fileName==""?"-":d.fileName}}</div>'
},
{
field
: 'fileSize',
title
: '附件大小',
minWidth
: 180,
align
: 'center',
templet
: '<div>{{(d.fileSize / 1024).toFixed(1)}}kb</div>'
},
{field
: 'opt', title
: '操作', fixed
: 'right', width
: 260, align
: 'center', toolbar
: '#toolBar'}
]],
url
: "back/hj/queryListPage",
contentType
: 'application/json',
method
: 'POST',
where
: {
condition
: {
"busId": busId
,
"fileName": $("#fileName").val()
}
},
request
: {
pageName
: 'current',
limitName
: 'size'
},
response
: {
statusCode
: 200,
msgName
: 'message'
},
elem
: '#hjTable',
page
: {
elem
: 'pageDiv',
limit
: 10,
}
});
table
.on('row(hjFilter)', function (obj
) {
obj
.tr
.addClass('layui-bg-light-green').siblings().removeClass('layui-bg-light-green');
});
table
.on('tool(hjFilter)', function (obj
) {
var data
= obj
.data
;
var layEvent
= obj
.event
;
if (layEvent
=== 'download') {
layer
.confirm('您确定要下载 ' + data
.fileName
+ ' 吗?', {icon
: 3, title
: '下载提示'}, function () {
index
= top
.layer
.msg('文件加载中,请稍候', {icon
: 16, time
: false, shade
: 0.8});
window
.location
.href
= requestLink
+ "back/hj/download?id=" + data
.id
;
layer
.closeAll('dialog');
top
.layer
.close(index
);
});
}
});
$(".search_btn").click(function () {
fileTableIns
.reload({
where
: {
condition
: {
"busId": busId
,
"fileName": $("#fileName").val()
}
},
page
: {
curr
: 1
}
});
});
upload
.render({
elem
: '#fileUpload',
size
: 1024 * 50,
url
: 'back/hj/uploading?busId=' + busId
,
accept
: 'file',
exts
: 'docx|docm|dotx|dotm|xlsx|xlsm|xltx|xltm|xlsb|xlam|pptx|pptm|ppsx|ppsx|potx|potm|ppam|pdf|PNG|JPEG|JPG|GIF',
before
: function (obj
) {
index
= top
.layer
.msg('文件上传中,请稍候', {icon
: 16, time
: false, shade
: 0.8});
},
progress
: function (n
, elem
) {
var percent
= n
+ '%'
console
.log(percent
);
},
done
: function (res
) {
top
.layer
.close(index
);
if (res
.code
== "200") {
layer
.msg('上传成功', {icon
: 1});
fileTableIns
.reload({page
: {curr
: 1}});
} else {
layer
.msg(res
.message
, {icon
: 2});
}
},
error
: function (index
, upload
) {
top
.layer
.close(index
);
layer
.msg("系统异常", {icon
: 2});
}
});
后台控制器
package com
.soa
.ump
.server
.controllerBack
;
import com
.soa
.common
.core
.constant
.Constant
;
import com
.soa
.common
.core
.constant
.SysConstant
;
import com
.soa
.common
.core
.model
.PageModel
;
import com
.soa
.common
.web
.model
.ResultModel
;
import com
.soa
.common
.web
.util
.ResultUtil
;
import com
.soa
.common
.web
.util
.ReturnUtilServer
;
import com
.soa
.ump
.server
.message
.CommonFileUtil
;
import io
.swagger
.annotations
.Api
;
import io
.swagger
.annotations
.ApiImplicitParam
;
import io
.swagger
.annotations
.ApiImplicitParams
;
import io
.swagger
.annotations
.ApiOperation
;
import org
.apache
.poi
.util
.IOUtils
;
import org
.springframework
.web
.bind
.annotation
.*;
import com
.soa
.common
.web
.BaseController
;
import com
.soa
.bus
.model
.HjAccessory
;
import com
.soa
.bus
.rpc
.api
.IHjAccessoryService
;
import org
.springframework
.beans
.factory
.annotation
.Autowired
;
import org
.springframework
.web
.multipart
.MultipartFile
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
import java
.io
.*;
import java
.util
.Arrays
;
import java
.util
.Map
;
@RestController
@
RequestMapping("/back/hj")
@
Api(value
= "HjController", description
= "附件上传下载管理Api")
public class HjController extends BaseController {
@Autowired
private CommonFileUtil commonFileUtil
;
private static final String
PREFIXED = "http://192.168.1.1/";
@
ApiOperation(value
= "上传附件", notes
= "上传附件")
@
ApiImplicitParams({
@
ApiImplicitParam(name
= "busId", value
= "业务Id", dataType
= "String", required
= true, paramType
= "query"),
})
@
PostMapping(value
= "/uploading")
public Map
<String
, Object
> saveTfAttachment(@
RequestParam("file") MultipartFile attachmentFile
, Long busId
) {
try {
long size
= attachmentFile
.getSize();
if (size
> (1024 * 1024 * 50)) {
return returnUtil
.returnMess(Constant
.OPERATION_FAILURE, "无法上传,单文件最大可上传50MB");
}
String attachmentOriginalName
= attachmentFile
.getOriginalFilename();
System
.out
.println("文件大小:" + attachmentFile
.getSize());
System
.out
.println("文件源名:" + attachmentOriginalName
);
System
.out
.println("type:" + busType
);
String filePath
= this.commonFileUtil
.uploadFile(attachmentFile
);
Hj accessory
= this.service
.add(new HjAccessory(busId
, attachmentOriginalName
, filePath
, PREFIXED, size
, super.getCurrentUserId()));
if (accessory
!= null) {
return returnUtil
.returnMess(accessory
.getId());
} else {
return returnUtil
.returnMess(Constant
.OPERATION_FAILURE);
}
} catch (Exception e
) {
e
.printStackTrace();
return returnUtil
.returnMess(Constant
.DATA_ERROR);
}
}
@
GetMapping("/download")
public void getDownload(Long id
, HttpServletRequest request
, HttpServletResponse response
) {
HjAccessory entity
= service
.selectById(id
);
try {
String headerKey
= "Content-Disposition";
String filename
= new String(entity
.getFileName().getBytes(), "ISO-8859-1");
String headerValue
= String
.format("attachment; filename=" + filename
);
response
.setHeader(headerKey
, headerValue
);
byte
[] download
= this.commonFileUtil
.download(entity
.getFilePath());
InputStream myStream
= new ByteArrayInputStream(download
);
IOUtils
.copy(myStream
, response
.getOutputStream());
response
.flushBuffer();
} catch (IOException e
) {
e
.printStackTrace();
}
}
工具类
package com
.soa
.ump
.server
.message
;
import com
.github
.tobato
.fastdfs
.domain
.MateData
;
import com
.github
.tobato
.fastdfs
.domain
.StorePath
;
import com
.github
.tobato
.fastdfs
.exception
.FdfsUnsupportStorePathException
;
import com
.github
.tobato
.fastdfs
.proto
.storage
.DownloadByteArray
;
import com
.github
.tobato
.fastdfs
.proto
.storage
.DownloadFileWriter
;
import com
.github
.tobato
.fastdfs
.service
.FastFileStorageClient
;
import com
.soa
.common
.tools
.StringUtil
;
import org
.apache
.commons
.io
.FilenameUtils
;
import org
.springframework
.beans
.factory
.annotation
.Autowired
;
import org
.springframework
.stereotype
.Component
;
import org
.springframework
.web
.multipart
.MultipartFile
;
import javax
.servlet
.http
.HttpServletResponse
;
import java
.io
.*;
import java
.nio
.charset
.Charset
;
import java
.util
.Set
;
@Component
public class CommonFileUtil {
@Autowired
private FastFileStorageClient fastFileStorageClient
;
public String
uploadFile(MultipartFile file
) throws IOException
{
StorePath storePath
= fastFileStorageClient
.uploadFile(file
.getInputStream(), file
.getSize(),
FilenameUtils
.getExtension(file
.getOriginalFilename()), null);
return getResAccessUrl(storePath
);
}
public String
uploadFile(File file
) throws IOException
{
FileInputStream inputStream
= new FileInputStream(file
);
StorePath path
= fastFileStorageClient
.uploadFile(inputStream
, file
.length(),
FilenameUtils
.getExtension(file
.getName()), null);
return getResAccessUrl(path
);
}
public String
uploadFileStream(InputStream is
, long size
, String fileName
) {
StorePath path
= fastFileStorageClient
.uploadFile(is
, size
, fileName
, null);
return getResAccessUrl(path
);
}
public String
uploadFile(String content
, String fileExtension
) {
byte
[] buff
= content
.getBytes(Charset
.forName("UTF-8"));
ByteArrayInputStream stream
= new ByteArrayInputStream(buff
);
StorePath path
= fastFileStorageClient
.uploadFile(stream
, buff
.length
, fileExtension
, null);
return getResAccessUrl(path
);
}
private String
getResAccessUrl(StorePath storePath
) {
return storePath
.getGroup() + "/" + storePath
.getPath();
}
public void deleteFile(String filePath
) {
if (StringUtil
.isEmpty(filePath
)) {
return;
}
try {
String group
= filePath
.substring(0, filePath
.indexOf("/"));
String path
= filePath
.substring(filePath
.indexOf("/") + 1);
StorePath storePath
= new StorePath(group
, path
);
fastFileStorageClient
.deleteFile(storePath
.getGroup(), storePath
.getPath());
} catch (FdfsUnsupportStorePathException e
) {
System
.out
.println("error" + e
.getMessage());
}
}
public byte
[] download(String filePath
) {
String group
= filePath
.substring(0, filePath
.indexOf("/"));
String path
= filePath
.substring(filePath
.indexOf("/") + 1);
DownloadByteArray downloadByteArray
= new DownloadByteArray();
byte
[] bytes
= this.fastFileStorageClient
.downloadFile(group
, path
, downloadByteArray
);
return bytes
;
}
}