最近基于若依框架做了一套后台管理系统,使用到上传和下载功能,一起学习和分享下;
上传功能
前端:
引入样式:
<th:block th:include="include :: bootstrap-fileinput-css"/>
然后div样式:
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div class="file-loading">
<input id="input-folder-3" type="file" name="file" multiple>
</div>
</div>
</div>
</div>
引入:
<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: datetimepicker-js"/>
必要时前端可以调试修改js,因为这个组件本身上传后有,上传、移除、阅览功能,若需要单个文件下载功能的可以自己调试。
然后是javascript:
<script type="text/javascript">
var prefix = ctx + "invoice/saleInvoice";
$("#form-info-edit").validate({
focusCleanup: true
});
function submitHandler() {
if ($.validate.form()) {
$.operate.save(prefix + "/applyOpenInvoice", $('#form-info-edit').serialize());
}
}
$(document).ready(function () {
$("#input-folder-3").fileinput({
uploadUrl: prefix + "/addFile",
uploadExtraData: function () {//向后台传递参数,需要根据id更新对应信息
var data = {
id: $("#id").val(),
};
return data;
},
// otherActionButtons: '<button type="button" class="kv-file-down btn btn-sm btn-default" {dataKey} onclick="downloadFile()" title="下载附件"><i class="fa fa-cloud-download"></i></button>',
uploadAsync: false,//false 同步上传,后台用数组接收,true 异步上传,每次上传一个file,会调用多次接口
showRemove: true,//显示移除按钮
showPreview: true,//是否显示预览
showCaption: true,//是否显示文字描述
maxFileCount: 10,//最大可选文件数
// removeFromPreviewOnError:true, //当选择的文件不符合规则时,例如不是指定后缀文件、大小超出配置等,选择的文件不会出现在预览框中,只会显示错误信息
// enctype: 'multipart/form-data',
// uploadExtraData: function () {//向后台传递参数
// var data = {
// apkName: $("#apkName").val(),
// versionNum: $("#versionNum").val(),
// description: $("#description").val()
// };
// return data;
// },
hideThumbnailContent: true // hide image, pdf, text or other content in the thumbnail preview
});
});
</script>
选中文件打开后,会出现移除和上传按钮,单个文件上也有单独移除、单独上传、阅览按钮,点击上传会调用到后台处理,
上传的后台逻辑:
直接看代码:
@PostMapping("/addFile")
@ResponseBody
public AjaxResult insert(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile[] file) throws Exception {
String id = request.getParameter("id");//当需对
logger.info("获取选中数据主键:{}", id);
if (file != null && file.length > 0) {
List<String> fileName = new ArrayList<String>();
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
try {
for (int i = 0; i < file.length; i++) {
if (!file[i].isEmpty()) {
//上传文件
fileName.add(uploadImage(request, filePath, file[i], false));
}
}
//上传成功
if (fileName != null && fileName.size() > 0) {
return AjaxResult.success("上传成功!");
} else {
return AjaxResult.error("上传失败!文件格式错误!");
}
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error("上传出现异常!");
}
} else {
return AjaxResult.error("未检测到文件!");
}
}
/**
* 上传文件
* 原名称
*
* @param request 请求
* @param path_deposit 存放位置(路径)
* @param file 文件
* @param isRandomName 是否随机名称
* @return 完整文件路径
*/
public String uploadImage(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName) {
try {
if (file != null) {
String origName = file.getOriginalFilename();// 文件原名称
System.out.println("上传的文件原名称:" + origName);
//路径+文件名称
String fileSrc = "";
//是否随机名称
if (isRandomName) {
origName = DateUtil.today() + UUID.randomUUID().toString() + origName.substring(origName.lastIndexOf("."));
}
// 上传并返回新文件名称
String fileNameNew = FileUploadUtils.upload(path_deposit, file);
logger.info("新文件名称:{}", fileNameNew);
//判断是否存在目录
// File targetFile = new File(path, origName);
// if (!targetFile.exists()) {
// targetFile.mkdirs();//创建目录
// }
// //上传
// file.transferTo(targetFile);
//完整路径
fileSrc = request.getContextPath() + path_deposit + origName;
logger.info("图片上传路径:{}", fileSrc);
return fileSrc;
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
这段代码方法 FileUploadUtils.upload主要执行的是 file.transferTo(targetFile),把文件格式校验,文件名称长度校验
,上传路径校验 什么的抽出来了。
下载功能:
前端代码:
后台附件信息表返回list多笔附件信息,前端需要foreach处理(也可以用什么js动态绑定,不会,所以。。。。)
<div class="row" >
<div class="col-sm-6" ><span style="color: red; ">点击下载附件</span>
<div th:each="invoiceFileInfo: ${invoiceFileInfoList}">
<input name="fileName" th:value="${invoiceFileInfo.fileName}" class="form-control"
type="text" readonly onclick="downloadFile(this.value)"><br/>
<!--<i class="fa fa-download" aria-hidden="true" title="下载"-->
<!--onclick="downloadFile()"></i>-->
</div>
</div>
</div>
function downloadFile(fileName) {
var fileCode = document.getElementById("fileCode").value;//附件编号
window.location.href = prefix + "/downloadFile/" + fileName + "/" + fileCode;
}
后台代码:
**
* 文件下载
*
* @param fileName,fileCode
* @param response
* @param request
* @throws Exception
*/
@GetMapping("/downloadFile/{fileName}/{fileCode}")
public void downloadFile(@PathVariable("fileName") String fileName, @PathVariable("fileCode") String fileCode, HttpServletResponse response,
HttpServletRequest request) throws Exception {
InvoiceFileInfo invoiceFile = invoiceFileInfoService.selectInvoiceFileInfoByCodeAndName(fileCode, fileName);
String filePath = invoiceFile.getFilePath();
String realFileName = invoiceFile.getFileName() + filePath.substring(filePath.indexOf("."));
// String path = RuoYiConfig.getUploadPath() + invoiceFile.getFilePath();
String path = invoiceFile.getFilePath();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
FileUtils.writeBytes(path, response.getOutputStream());
}
学习主要参考若依官网文档,大差不差,仅供参考。