1、pom文件引入依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
2、引入js和css
<link rel="stylesheet" type="text/css" href="/libs/bootstrap_fileinput/css/fileinput.min.css">
<script src="/libs/bootstrap_fileinput/js/fileinput.min.js"></script>
<script src="/libs/bootstrap_fileinput/js/fileinput_locale_zh.js"></script>
3、页面
<div class="card card-info">
<div class="card-header">
<h3 class="card-title">商品图片</h3>
</div>
<div class="card-body">
<a href="" class="form-control" style="border:none;">下载模板</a>
<input type="file" name="reportFile" id="reportFile" multiple class="file-loading" />
</div>
</div>
4、javascript初始化上传
jQuery(function($){
//初始化图片上传 参数1:控件id、参数2:上传地址
initFileInput("reportFile", pt.base+"report/uploadReport");
});
//初始化fileinput控件(第一次初始化)
function initFileInput(ctrlName, uploadUrl) {
var control = $('#' + ctrlName);
//初始化上传控件的样式
control.fileinput({
language: 'zh', //设置语言
uploadUrl: uploadUrl, //上传的地址
allowedFileExtensions: ['jpg', 'gif', 'png', 'pdf'], //接收的文件后缀
showUpload: true, //是否显示上传按钮
showRemove : true, //显示移除按钮
showPreview : true, //是否显示预览
showCaption: false, //是否显示标题
browseClass: "btn btn-primary", //按钮样式
uploadAsync: true, //默认异步上传
//dropZoneEnabled: false, //是否显示拖拽区域
//minImageWidth: 50, //图片的最小宽度
//minImageHeight: 50, //图片的最小高度
//maxImageWidth: 1000, //图片的最大宽度
//maxImageHeight: 1000, //图片的最大高度
//maxFileSize: 0, //单位为kb,如果为0表示不限制文件大小
//minFileCount: 0,
maxFileCount: 3, //表示允许同时上传的最大文件个数
enctype: 'multipart/form-data',
validateInitialCount:true,
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
uploadExtraData:function (previewId, index) { //传参
var data = {
"reportGroupId": $('#lbl_groupId').html(), //此处自定义传参
};
return data;
}
});
//导入文件上传完成之后的事件
control.on('fileuploaded', function(event, data, previewId, index){
var response = data.response;
$.each(response,function(id,path){//上传完毕,将文件名返回
console.log("path:"+path.pathUrl);
$("#form").append("<input class='imgClass' name='filePath' type='hidden' value='"+path.pathUrl+"'>");
});
});
}
5、控制层
package com.st.project.controller;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static com.st.project.common.DateUtil.getCurrentTime;
/**
* 文件上传Controller
*/
@Controller
@RequestMapping("/report")
public class UploaderController {
private static Logger logger= LoggerFactory.getLogger(UploaderController.class);
@Value("${portals.upload.image.path}")
private String imagePath; //图片存储路径
private String userId="who"; //登陆用户
@PostMapping("/uploadReport")
@ResponseBody
public List<Map<String,String>> upload(@RequestParam MultipartFile[] reportFile,HttpServletRequest request,HttpServletResponse response) throws IOException{
String day = getCurrentTime("yyyyMMdd");//获取当前天
String realPath =imagePath; //图片存储路径
File file = new File(realPath);
if (!file.exists()) {//文件夹不存在 创建文件夹
file.mkdirs();
}
response.setContentType("text/plain; charset=UTF-8");
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
String originalFilename = null;
for(MultipartFile myfile : reportFile){
Map<String,String> map = new HashMap<String,String>();
if(myfile.isEmpty()){
logger.info("请选择文件后上传!");
return null;
}else{
originalFilename = myfile.getOriginalFilename();
String extension =FilenameUtils.getExtension(originalFilename);
if("jpg".equalsIgnoreCase(extension)||"png".equalsIgnoreCase(extension)){
originalFilename=userId+"_"+System.currentTimeMillis()+"."+FilenameUtils.getExtension(originalFilename);
try {
myfile.transferTo(new File(realPath, originalFilename));
//保存文件路径
map.put("pathUrl",originalFilename);
list.add(map);
logger.info("load success " + request.getContextPath()+File.separator+"upload"+File.separator+day+File.separator+originalFilename);
logger.info("leaving upload!");
}catch (Exception e) {
logger.info("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
e.printStackTrace();
logger.info("文件上传失败,请重试!!");
return null;
}
}else{
logger.info("load success 只支持jpg,png格式");
}
}
}
return list;
}
}