这段时间有个项目前端需要用到图片上传的功能,在找了很久之后终于找到了bootstrap的开源插件bootstrap-fileinput,这款开源插件也很好适配了我项目中用到的bootstrap框架,所以就开始了跳坑和填坑的道路。由于本人还是个菜鸟,所以在这个插件中摸索了比较久,写这个博客一是想给不会用的同学分享一下我自己摸索出来的方法,二是记录下BootStrap-fileinput前端和后端的用法,防止以后忘记也有资料可以查。
插件及jar包下载
BootStrap-fileinput插件下载
依赖的jar包有:
commons-fileupload-1.2.jar
commons-io-2.6.jar
gson-2.3.1.jar
除了这些包之外我还用到struts2框架,需要的同学自行下载,这里就不一一列出来了
引入插件文件
导入css文件:
导入js文件(为了中文化需要导入zh.js,如果没有导入这个包文件上传框会是英文的。需要注意的是zh.js必须要 在fileinput.js的后面,否则无法中文化):
<script type="text/javascript" src="js/fileinput.js"></script> <script type="text/javascript" src="js/zh.js"></script>
前端代码
HTML代码
HTML需要的东西很简单一个带id、带name、type为file的input就可以:
js代码,js代码里面包括了文件上传的回调函数和配置等:
$("#img").fileinput({ language : 'zh',//设置文中文 uploadUrl : "uploadImg",//图片上传的url,我这里对应的是后台struts配置好的的action方法 showCaption : true,//显示标题 showRemove : true, //显示移除按钮 uploadAsync : true,//默认异步上传 showPreview : true,//是否显示预览 textEncoding : "UTF-8",//文本编码 autoReplaceBoolean : false,//选择图片时不清空原图片 }); $("#img").on('fileuploaded', function(event, data, previewId, index) {//异步上传成功结果处理 var img= JSON.parse(data.response);//接收后台传过来的json数据 alert(img.imgUrl); }); $("#img").on('fileerror', function(event, data, msg) {//异步上传失败结果处理 alert("uploadError"); });
java代码:
action方法:
package com.minxuan.mitesofor.action; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.google.gson.Gson; import com.minxuan.mitesofor.domian.ServiceManDO; import com.minxuan.mitesofor.service.ServiceManService; import com.minxuan.mitesofor.serviceImpl.ServiceManServiceImpl; import com.minxuan.mitesofor.util.UploadUtil; /** * @author xionglinyong * @see 文件上传Action */ public class UploadAction { private File img; private String imgFileName; public File getImg() { return img; } public void setImg(File img) { this.img = img; } public String getImgFileName() { return imgFileName; } public void setImgFileName(String imgFileName) { this.imgFileName = imgFileName; } public void uploadImg() { // 调用文件上传工具类中的文件上传方法,img和前端input的name相对应 String imgPath = UploadUtil.uploadImg(getImg(), getImgFileName()); HttpServletResponse response = ServletActionContext.getResponse(); PrintWriter out = null; String jsonString = "{\"imgUrl\":\"" + imgPath + "\"}";//定义json字符串 Gson json = new Gson();//定义json对象 try { out = response.getWriter(); out.print(json.toJson(jsonString));//将json字符串转换为JSON对象,并向前端输出 out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
文件上传工具类:
package com.minxuan.mitesofor.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; public class UploadUtil { public static String uploadImg(File img,String imgFileName) { String folderPath=""; String imgUrl = "";//返回的图片地址 HttpServletRequest request = ServletActionContext.getRequest();//获取request对象 StringBuffer url1 = request.getRequestURL();//获取当前页面的URL String tempContextUrl1 = url1.delete(url1.length() - request.getRequestURI().length(), url1.length()) .append("/").toString();//当前页面的URL减去当前页面的地址为http头 String p = request.getRealPath("/img/upload");//得到站点的绝对地址 String path; String fileName = UUID.randomUUID().toString() + imgFileName.substring(imgFileName.lastIndexOf("."));//生成随机图片名称 int length; path = p + "\\" + fileName;//图片地址全 try { FileOutputStream fos = new FileOutputStream(path); FileInputStream fis = new FileInputStream(img); byte[] buffer = new byte[1024 * 1024 * 20]; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } fos.close(); fis.close(); imgUrl = tempContextUrl1 + request.getContextPath() + "/img/upload/" + fileName; } catch (FileNotFoundException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return imgUrl; // 返回url地址 } }
完整的相关代码就已经写好了,需要注意的是:
bootstrap fileinput返回数据类型只接收json对象,其他格式的数据会报错,文件能够上传,只是显示的信息不太友好
后台传入请前台的json字符串中一定要严格按照"{\"imgUrl\":\"imgPath\"}"的格式,否则方法JSON.parse(data.response)无法将data中的json字符串解析为json对象(有人想问了,能否直接data.imgUrl呢,当然是不行的,我已经 试了好几遍了。当然能够用其他方式获取数据的大神可以评论说说你是怎么获取后台返回的图片链接的)
最后声明一下,作者菜鸟,有写的不到位的地方请大佬们指出