懒得写页面 于是我经常使用bootstrap,其中关于上传 有个fileinput的js插件可以专门用在bootstrap上 效果非常不错,经过了一段时间的研究终于能在jsp+servlet的环境下运行了,以此来写一篇博客,记录一下,以防忘记。
首先准备相关的js 及 jar包
<link rel="stylesheet" href="/Education/resources/css/bootstrap.css">//bootstrap<link rel="stylesheet" href="/Education/resources/css/fileinput.css">//bootstrap_fileinput
<script src="/Education/resources/js/jquery-2.2.1.min.js"></script>//jquery
<script src="/Education/resources/js/bootstrap.js"></script>//bootstrap
<script src="/Education/resources/js/fileinput.js"></script>//bootstrap_fileinput
<script src="/Education/resources/js/zh.js"></script>//bootstrap_fileinput 中文
commons-fileupload-1.3.2.jar
commons-io-2.2.jar
fastjson-1.2.23
准备工作完成后 该打代码了
HTML部分:
<input id="headImg" name="headImg" class="file" type="file" multiple />
因为这是json提交 没有form表单也行;
JS 部分:
<script type="text/javascript">
//初始化fileinput控件(第一次初始化)
function initFileInput(ctrlName, uploadUrl) {
var control = $('#' + ctrlName);
control.fileinput({
language: 'zh', //设置语言
uploadUrl: uploadUrl, //上传的地址
allowedFileExtensions : ['jpg', 'png','gif',"avi"],//接收的文件后缀
showUpload: true, //是否显示上传按钮
showCaption: false,//是否显示标题
browseClass: "btn btn-primary", //按钮样式
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
});
}
initFileInput("headImg","/Education/UploadImgServlet");
</script>
Servlet部分:
System.out.println("上传开始");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
String savePath=this.getServletContext().getRealPath("/")+"upload/";
System.out.println("---savePath="+savePath);
try {
List<FileItem> items = upload.parseRequest(request);
for(FileItem item:items){
if (!item.isFormField()) {
String fileName = item.getName();
File uploadedFile = new File(savePath+fileName);
try {
item.write(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("result", "ok");
response.getWriter().write(jsonObject.toString());
System.out.println("上传结束");