Bootstrap中的fileinput 多图片上传及编辑功能

网友投稿 887 2023-07-07


Bootstrap中的fileinput 多图片上传及编辑功能

大家如果对Bootstrap-fileinput 的配置不清楚的话,大家可以查看官方网站:http://plugins.krajee.com/file-input。

逻辑说明:先从后台获取数据展示,然后进行编辑。

废话不多说, 直接上代码.

1. 页面部分代码:

说明: 其中onchange()为我业务需要, 上传完成后自动执行一个添加事件。 此方法可以去掉。

2. 获取初始化数据方法:

// 初始化获取原有文件

$(function(){

$.ajax({

type : "post",

url : "/eim/project/testFileUpload.do",

dataType : "json",

success : function(data) {

layer.msg('操作成功!');

showPhotos(data);

},

error: function(XMLHttpRequest, textStatus, errorThrown) {

layer.msg('操作失败!');

}

});

});

说明:此处我返回是一个 对象数组:List,可以理解为获取一个班中所有的学生,展示头像

3.初始化bootstrap-fileinput 组件:

function showPhotos(djson){

//后台返回json字符串转换为json对象

var reData = eval(djson);

// 预览图片json数据组

var preList = new Array();

for ( var i = 0; i < reData.length; i++) {

var array_element = reData[i];

// 此处指针对.txt判断,其余自行添加

if(array_element.fileIdFile.name.indexOf("txt")>0){

// 非图片类型的展示

preList[i]= "

}else{

// 图片类型

preList[i]= "";

}

}

var previewJson = preList;

// 与上面 预览图片json数据组 对应的config数据

var preConfigList = new Array();

for ( var i = 0; i < reData.length; i++) {

var array_element = reData[i];

var tjson = {caption: array_element.fileIdFile.fileName, // 展示的文件名

width: '120px',

url: '/eim/project/deleteFile.do', // 删除url

key: array_element.id, // 删除是Ajax向后台传递的参数

extra: {id: 100}

};

preConfigList[i] = tjson;

}

// 具体参数自行查询

$('#testlogo').fileinput({

uploadUrl: '/eim/upload/uploadFile.do',

uploadAsync:true,

showCaption: true,

showUpload: true,//是否显示上传按钮

showRemove: false,//是否显示删除按钮

showCaption: true,//是否显示输入框

showPreview:true,

showCancel:true,

dropZoneEnabled: false,

maxFileCount: 10,

initialPreviewShowDelete:true,

msgFilesTooMany: "选择上传的文件数量 超过允许的最大数值!",

initialPreview: previewJson,

previewFileIcon: '',

allowedPreviewTypes: ['image'],

previewFileIconSettings: {

'docx': '',

'xlsx': '',

'pptx': '',

'pdf': '',

'zip': '',

'sql': '',

},

initialPreviewConfig: preConfigList

}).off('filepreupload').on('filepreupload', function() {

// alert(data.url);

}).on("fileuploaded", function(event, outData) {

//文件上传成功后返回的数据, 此处我只保存返回文件的id

var result = outData.response.id;

// 对应的input 赋值

$('#htestlogo').val(result).change();

});

}

4. 后台java保存文件部分代码

@RequestMapping(value="/uploadFile",method=RequestMethod.POST)

@ResponseBody

public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//转型为MultipartHttpServletRequest

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;

//获取文件到map容器中

Map fileMap = multipartRequest.getFileMap();

//获取页面传递过来的路径参数

folderPath = request.getParameter("folder");

String rootPath = BaseConfig.uploadPath;

String filePath = rootPath + folderPath+"/";

//文件上传并返回map容器,map存储了文件信息

FileModel fileModel = UploadifyUtils.uploadFiles(filePath,fileMap);

boolean flag = service.add(fileModel);

if(flag){

String result = fileModel.getId()+";"+fileModel.getFilePath()+";"+fileModel.getName()+";"+fileModel.getFilePath();

Mahttp://p map = new HashMap<>();

map.put("id", fileModel.getId());

//返回文件保存ID

//response.getWriter().write(map);

return map;

}

return null;

}

说明:该段代码为获取上传文件的部分信息, 如文件名,上传的路径 等,将文件信息保存到表中,对应对象为 FileModel 。

5.上传完成后重新刷新该组件即可。

最终展示效果 :

说明:此处指针对txt文件类型判断, 其余的doc,ppt里面有对应的展示图标,只须在判断是添加对应样式即可

附:根据路径过去/下载文件代码:

/**

* 文件下载

*

* @param savePath

* 保存目录

* @param name

* 文件原名

* @param file

* 保存时的名称 包含后缀

* @param request

* @param response

* @return

*/

public static String down(String savePath, String name, String fileName, HttpServletRequest request,

HttpServletResponse response) {

try {

String path = savePath + "/" + name;

File file = new File(path);

if (!file.exists()) {

// 不存在

request.setAttribute("name", fileName);

return "download_error";// 返回下载文件不存在

}

response.setContentType("application/octet-stream");

// 根据不同浏览器 设置response的Header

String userAgent = request.getHeader("User-Agent").toLowerCase();

if (userAgent.indexOf("msie") != -1) {

// ie浏览器

// System.out.println("ie浏览器");

response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));

} else {

response.addHeader("Content-Disposition",

"attachment;filename=" + new String(name.getBytes("utf-8"), "ISO8859-1"));

}

response.addHeader("Content-Length", "" + file.length());

// 以流的形式下载文件

InputStream fis = new BufferedInputStream(new FileInputStream(path));

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

fis.close();

//response.setContentType("image/*"); // 设置返回的文件类型

OutputStream toClient = response.getOutputStream();

OutputStream bos = new BufferedOutputStream(toClient);

//BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(bos));

bos.write(buffer);

//bw.close();

bos.close();

toClient.close();

return null;

} catch (Exception e) {

e.printStackTrace();

//response.reset();

return "exception";// 返回异常页面

} finally {

/* if (toClient != null) {

try {

toClient.close();

} catch (IOException e) {

e.printStackTrace();

}

}*/

}

}

附:

UploadifyUtils.uploadFiles 部分代码

public static FileModel uploadFiles(String savePath,Map fiLeMap){

//上传文件

//附件模型对象

FileModel fm=new FileModel();

try {

File file = new File(savePath);

//判断文件夹是否存在,如果不存在则创建文件夹

makeDir(file);

if(fiLeMap!=null){

for(Map.Entry entity:fiLeMap.entrySet()){

MultipartFile f = entity.getValue();

if(f!=null&&!f.isEmpty()){

String uuid=UploadifyUtils.getUUID();//uuid作为保存时的文件名

String ext=UploadifyUtils.getFileExt(f.getOriginalFilename());//获取文件后缀

//保存文件

File newFile = new File(savePath+"/"+uuid+"."+ext);

f.transferTo(newFile);

fm.setFileName(f.getOriginalFilename());

fm.setName(uuid+"."+ext);

fm.setFilePath(savePath);//保存路径

fm.setExhttp://t(ext);

fm.setSize(f.getSize());

}

}

}

return fm;

}catch (Exception e) {

log.error(e);

return null;

}

}

以上所述是给大家介绍的Bootstrap中的fileinput 多图片上传编辑,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Bootstrap的fileinput插件实现多文件上传的方法
下一篇:Java中replace、replaceAll和replaceFirst函数的用法小结
相关文章

 发表评论

暂时没有评论,来抢沙发吧~