需引入fileinput.js和fileinput.min.css,地址:https://gitee.com/jolone/source.git
<div class="change_Pass_style" id="fileUpload">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel" th:text="${model.selectApk}">请选择apk文件</h4>
</div>
<div class="modal-body">
<input type="file" name="txt_file" id="txt_file" multiple class="file-loading" />
</div></div>
</div>
</div>
$(function () {
//初始化fileinput
var oFileInput = new FileInput();
oFileInput.Init("txt_file", "/api/OrderApi/ImportOrder");
});
var cabinet_id = '';
var FileInput = function () {
var oFile = new Object();
//初始化fileinput控件(第一次初始化)
oFile.Init = function(ctrlName, uploadUrl) {
var control = $('#' + ctrlName);
//初始化上传控件的样式
control.fileinput({
language: 'en', //设置语言
uploadUrl: 'sysUploadSoftware', //上传的地址
allowedFileExtensions: ['jpg', 'png', 'apk'],//接收的文件后缀
showUpload: true, //是否显示上传按钮
showCaption: false,//是否显示标题
browseClass: "btn btn-primary", //按钮样式
//dropZoneEnabled: false,//是否显示拖拽区域
//minImageWidth: 50, //图片的最小宽度
//minImageHeight: 50,//图片的最小高度
//maxImageWidth: 1000,//图片的最大宽度
//maxImageHeight: 1000,//图片的最大高度
maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
//minFileCount: 0,
maxFileCount: 10, //表示允许同时上传的最大文件个数
enctype: 'multipart/form-data',
validateInitialCount:true,
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
msgFilesTooMany: "选择上传的文件数量过多",
uploadExtraData:function(){//向后台传递参数
var data={
cabinetId:cabinet_id
};
return data;
},
});
cabinet_id = '';
//导入文件上传完成之后的事件
$("#txt_file").on("fileuploaded", function (event, data, previewId, index) {
$("#myModal").modal("hide");
var data = data.response.lstOrderImport;
if (data == undefined) {
toastr.error('文件格式类型不正确');
return;
}
//1.初始化表格
var oTable = new TableInit();
oTable.Init(data);
$("#div_startimport").show();
});
}
return oFile;
};
文件过大时,修改Tomcat默认文件大小
package com.ys.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.MultipartConfigElement;
@Configuration
public class TomcatConfig {
@Value("${spring.server.MaxFileSize}")
private String MaxFileSize;
@Value("${spring.server.MaxRequestSize}")
private String MaxRequestSize;
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 单个数据大小
factory.setMaxFileSize(MaxFileSize); // KB,MB
/// 总上传数据大小
factory.setMaxRequestSize(MaxRequestSize);
return factory.createMultipartConfig();
}
}
application配置文件
spring.server.MaxFileSize=300MB
spring.server.MaxRequestSize=500MB
获取项目目录,后端保存
@PostMapping("sysUploadSoftware")
@ResponseBody
public JsonResult sysUploadSoftware(@RequestParam(value = "txt_file")MultipartFile multipartFile,@RequestParam(value = "cabinetId")String cabientId){
JsonResult json = new JsonResult();
json.setOk(false);
try{
String fileName = multipartFile.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//获取跟目录
// File path = new File(ResourceUtils.getURL("classpath:").getPath());
File upload = new File(PagesConfig.FILE_PATH);
if(!upload.exists()) upload.mkdirs();
json.setOk(true);
multipartFile.transferTo(new File(PagesConfig.FILE_PATH + fileName));
return json;
}catch (Exception e){
json.setOk(false);
return json;
}
}
下载后端代码
public void sysDownloadSoftware(HttpServletResponse response, @RequestParam(value = "cabinetId") String cabientId) throws Exception {
Software software = softwareService.selectByCabientId(cabientId);
if (StringUtils.isNull(software)){
return;
}
File file = new File(software.getUrl());
String fileName = software.getCurrentVersion();
if (file.exists()) {
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName+";filename*=utf-8''"+ URLEncoder.encode(fileName,"UTF-8"));
///设置文件名编码格式
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream outputStream = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}