前言
这段时间空余时间研究了一下图片上传,使用fileinput插件,网上的例子只有前端提交上传,没有后端接收和处理图片,最后我成功实现以后我想把他记录下来,好记性不如烂笔头,先给大家看看效果:
1、一个简单的主界面,bootstrap做的,freemarker做界面数据渲染,实现了分页,批删,修改,删除,添加的功能,图片上传用在添加和修改中,主界面如下图:
当我点击添加按钮跳转到新增界面:
先上传,再提交,即可;
2、实现的步骤:导入fileinput的js和css自己解决
前端代码:
<div class="form-group">
<label class="col-sm-2 control-label">图片上传</label>
<div class="col-sm-4">
<input id="input-file" name="file" multiple type="file" data-show-
caption="true">
</div>
</div>
// 文件上传
$(function () {
initFileInput("input-file");
})
function initFileInput(ctrlName) {
var imags = new Array();
var control = $('#' + ctrlName);
control.fileinput({
language: 'zh', //设置语言
uploadUrl: "/commodity/uploads", //上传的地址
allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
//uploadExtraData:{"id": 1, "fileName":'123.mp3'},
uploadAsync: true, //默认异步上传
showUpload: true, //是否显示上传按钮
showRemove : true, //显示移除按钮
showPreview : true, //是否显示预览
showCaption: false,//是否显示标题
browseClass: "btn btn-primary", //按钮样式
//dropZoneEnabled: true,//是否显示拖拽区域
//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: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
}).on('filepreupload', function(event, data, previewId, index) { //上传中
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log('文件正在上传');
}).on("fileuploaded", function (event, data, previewId, index) { //一个文件上传成功
var response = data.response;
//alert(response.filePath);
imags.push(response.filePath)
$("#images").val(imags);
console.log('文件上传成功!'+data.id);
}).on('fileerror', function(event, data, msg) { //一个文件上传失败
console.log('文件上传失败!'+data.id);
})
}
后端controller实现:
/**
* 文件上传
* @param file
* @param request
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/uploads",method = RequestMethod.POST)
public Map<String,Object> uploads(MultipartFile file,HttpServletRequest request) throws Exception{
Map<String, Object> map = new HashMap();
File targetFile=null;
//返回存储路径
String filePath="";
int code=1;
System.out.println(file);
//获取文件名加后缀
String fileName = file.getOriginalFilename();
if(fileName != null && fileName != ""){
//图片访问的URI
String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";
//文件临时存储位置
String path = request.getSession().getServletContext().getRealPath("") + "upload" + File.separator + "imgs";
//文件后缀
String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
//新的文件名
fileName = System.currentTimeMillis()+"_"+new Random().nextInt(1000) + fileSuffix;
//先判断文件是否存在
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String fileAdd = sdf.format(new Date());
//获取文件夹路径
path = path + File.separator + fileAdd + File.separator;
File file1 =new File(path);
//如果文件夹不存在则创建
if(!file1 .exists() && !file1 .isDirectory()){
file1 .mkdirs();
}
//将图片存入文件夹
targetFile = new File(file1, fileName);
try {
//将上传的文件写到服务器上指定的文件。
file.transferTo(targetFile);
String projectPath = System.getProperty("user.dir");
//文件复制
String src = path + fileName;
//根据自己系统的resource 目录所在位置进行自行配置
//E:\hhf\develop20190805\mall\src\main\resources
String destDir = projectPath + File.separator+"src"+File.separator+"main"+ File.separator +"resources"+File.separator+"static"+ File.separator+"upload"+File.separator+"imgs" + File.separator + fileAdd + File.separator;
copyFile(src,destDir,fileName);
filePath= returnUrl + fileAdd + "/"+ fileName;
code=0;
map.put("filePath", filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
/**
* 复制文件
* @param src
* @param destDir
* @param fileName
* @throws IOException
*/
public void copyFile(String src,String destDir,String fileName) throws IOException{
FileInputStream in=new FileInputStream(src);
File fileDir = new File(destDir);
if(!fileDir.isDirectory()){
fileDir.mkdirs();
}
File file = new File(fileDir,fileName);
if(!file.exists()){
file.createNewFile();
}
FileOutputStream out=new FileOutputStream(file);
int c;
byte buffer[]=new byte[1024];
while((c=in.read(buffer))!=-1){
for(int i=0;i<c;i++){
out.write(buffer[i]);
}
}
in.close();
out.close();
}
注意:如果是多个文件,返回路径的时候,将路径添加到一个数组里边就行了,我就是这么实现的,点提交后把路径传到后台,插入数据库就行了,写的不是很详细,有不明白的地方可以留言交流,希望博友们支出不足的地方,感谢!
完整代码和数据库脚本下载地址:https://github.com/Huanghengfeng/PersonProject.git