上传使用layui组件
/**
* 文件上传路径映射类
* @author guoanhao
* @since 2021-03-22 19:15:09
* @ConfigurationProperties:前缀
*/
@Component
@ConfigurationProperties(prefix = "file")
@Data
public class FileUpload {
/**
* 文件上传路径
*/
@Value("${file.uploadPath}")
private String fileUploadPath;
}
/**
* 附件上传
* @param fileStr
* @param request
* @param response
* @return
*/
@PostMapping("/uploadFiles")
private ResponseResult uploadFile(
@RequestParam("file") MultipartFile[] fileStr,
HttpServletRequest request,
HttpServletResponse response){
//获取配置文件中的目录
String fileSpace = fileUpload.getFileUploadPath();
// 在路径下为每一个用户增加一个userId,用于区分不同用户上传
String uploadPathPrefix = File.separator;
EquipFile filesResult = new EquipFile();
// 回显文件id,多个文件则回显多个
Long[] ids = new Long[fileStr.length];
// fileStr.get
// 多文件上传,单个文件上传的话去掉for循环
for (MultipartFile file: fileStr) {
// i用于ids的回显
int i =0;
if (file != null) {
FileOutputStream fileOutputStream = null;
try {
// 获得文件上传的文件名称
String fileName = file.getOriginalFilename();
if (StringUtils.isNotBlank(fileName)) {
// 文件重命名 123.png -> ["123","png"]
String[] fileNameArr = fileName.split("\\.");
// 获取文件的后缀名
String suffix = fileNameArr[fileNameArr.length - 1];
// 上传的文件最终保存的位置,File.separator为斜杠的代码写法
String finalPath = fileSpace +"/"+ fileName;
// 用于提供给web服務訪問的地址
uploadPathPrefix += ("/" + fileName);
File outFile = new File("D:/"+finalPath);
if (outFile.getParentFile() != null) {
// 创建文件夹
outFile.getParentFile().mkdirs();
}
// 文件输出保存到目录
fileOutputStream = new FileOutputStream(outFile);
InputStream inputStream = file.getInputStream();
// 文件保存
IOUtils.copy(inputStream, fileOutputStream);
// face-{id}.xxx
// 更新附件到数据库
filesResult = equipFileService.uploadFile(fileName,
finalPath,suffix);
ids[i] = filesResult.getId();
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
return ResponseResult.success("文件不能为空");
}
}
return ResponseResult.success(ids);
}
/**
* 下载文件(UploadConfig)配置文件
*
* @author 郭安浩
* @since 2021-02-24 14:18:32
*/
@Configuration
public class UploadConfig {
@Bean(name="multipartResolver")
public MultipartResolver multipartResolver(){
return new CommonsMultipartResolver();
}
}
/**
* 下载
* @param filePath
* @param fileName
* @param response
* @param request
* @throws IOException
*/
@RequestMapping(value = "/downloadFile")
public void download(@RequestParam(name = "filePath",required = true) String filePath,
@RequestParam(name = "fileName",required = true) String fileName,
HttpServletResponse response,
HttpServletRequest request) throws IOException{
//获取服务器文件
File file = new File(filePath);
InputStream ins = new FileInputStream(file);
/* 设置文件ContentType类型,这样设置,会自动判断下载文件类型 */
response.setContentType("multipart/form-data");
/* 设置文件头:最后一个参数是设置下载文件名,文件名需要编码,不然中文不显示 */
String encodeFileName = new String(fileName.getBytes(),"ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+encodeFileName);
try{
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len;
while((len = ins.read(b)) > 0){
os.write(b,0,len);
}
os.flush();
os.close();
ins.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
/**
* 页面访问静态资源配置类
* @author guoanhao
*/
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
/**
* /image/**:页面中文件路径之前要加上/image/
* file:D:/workspaces/downloadFiles/:本地文件路径
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/image/**").addResourceLocations("file:D:/workspaces/downloadFiles/");
}
}
<form class="layui-form" action="" lay-filter="example">
<div class="layui-upload">
<div class="layui-upload-list">
<table class="layui-table" id="layuiTable">
<thead>
<tr><th>文件名</th>
<!-- <th>大小</th>-->
<th>状态</th>
<th>操作</th>
</tr></thead>
<tbody id="demoList"></tbody>
</table>
</div>
</div>
</form>
// 表单赋值
$.ajax({
type: "GET",
dataType: "json",
async: false,
url: 'equipInformation/queryOne',
data: {
id: id
},
success: function (data) {
var res = data.data;
var obj = data.data.fileList;
form.val("example",{
equipClassName:res.equipClassName,
equipFactoryName:res.equipFactoryName,
equipName:res.equipName,
productName:res.productName,
treatyName:res.treatyName
});
//附件
if (obj != null && obj.length != 0) {
for (var i = 0; i < obj.length; i++) {
var tr = $(['+ obj[i].id + '">',
'' + obj[i].fileName + ' ',
'已上传 ',
'',
'',
'+ obj[i].fileName + '&filePath=' + encodeURIComponent(obj[i].filePath) + '">下载',
' ',
' '].join(''));
$('#demoList').append(tr);
}
}
form.render(); //更新全部
}
})
页面代码,用的layui
// 预览文件图片,fileName是文件名。images是配置类中的配置路径,映射到本地文件夹中。
function previewImg(fileName) {
// 配置的本地路径
var imgHtml = "
";
//弹出层
parent.layer.open({
type: 1,
shade: 0.8,
offset: 'auto',
area: ['90%','90%'], // area: [width + 'px',height+'px'] //原图显示
shadeClose:true,
scrollbar: false,
title: "图片预览", //显示标题
content: imgHtml, //捕获的元素,注意:最好该指定的元素要存放在body最外层,否则可能被其它的相对元素所影响
cancel: function () {
//layer.msg('捕获就是从页面已经存在的元素上,包裹layer的结构', { time: 5000, icon: 6 });
}
,end:function (){
}
});
}
// 预览视频
function previewVideo(fileName) {
// 配置的本地路径
var html = '';
html += ';
html += '+ fileName+'" type="video/mp4" />';
html += '';
html += '';
//弹出层
parent.layer.open({
type: 1,
skin: 'layui-layer-rim', //加上边框
title: "视频预览",
content: html
});
}