JAVA图片批量上传JS-带预览功能
这篇文章就简单的介绍一个很好用的文件上传工具,批量带预览功能。直接贴代码吧,都有注释,很好理解。
HTML页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | <! DOCTYPE html> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> < html > < head > < c:set var="BASE" value="${pageContext.request.contextPath}"/> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> < meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> < title >新增照片</ title > < script type="text/javascript"> var BASE = "${BASE}"; </ script > <!-- 引用控制层插件样式 --> < link rel="stylesheet" href="${BASE}/www/css/upload/zyupload-1.0.0.min.css " type="text/css"> < script type="text/javascript" src="${BASE}/www/js/jquery-1.8.3.min.js"></ script > < script type="text/javascript" src="${BASE}/www/js/upload/zyupload-1.0.0.min.js"></ script > </ head > < body > < input type="hidden" id="boxId" value="${boxId}"/> < div id="zyupload" class="zyupload"></ div > < script type="text/javascript"> $(function(){ var boxId = $("#boxId").val(); // 初始化插件 $("#zyupload").zyUpload({ width : "650px", // 宽度 height : "400px", // 宽度 itemWidth : "140px", // 文件项的宽度 itemHeight : "115px", // 文件项的高度 url : BASE+"/photo/add/"+boxId, // 上传文件的路径 fileType : ["jpg","png","txt","js","exe","gif"],// 上传文件的类型 fileSize : 51200000, // 上传文件的大小 multiple : true, // 是否可以多个文件上传 dragDrop : true, // 是否可以拖动上传文件 tailor : true, // 是否可以裁剪图片 del : true, // 是否可以删除文件 finishDel : false, // 是否在上传文件完成后删除预览 /* 外部获得的回调接口 */ onSelect: function(selectFiles, allFiles){ // 选择文件的回调方法 selectFile:当前选中的文件 allFiles:还没上传的全部文件 console.info("当前选择了以下文件:"); console.info(selectFiles); }, onDelete: function(file, files){ // 删除一个文件的回调方法 file:当前删除的文件 files:删除之后的文件 console.info("当前删除了此文件:"); console.info(file.name); }, onSuccess: function(file, response){ // 文件上传成功的回调方法 console.info("此文件上传成功:"); console.info(file.name); console.info("此文件上传到服务器地址:"); console.info(response); $("#uploadInf").append("< p >上传成功,文件地址是:" + response + "</ p >"); }, onFailure: function(file, response){ // 文件上传失败的回调方法 console.info("此文件上传失败:"); console.info(file.name); }, onComplete: function(response){ // 上传完成的回调方法 console.info("文件上传完成"); console.info(response); } }); }); </ script > </ body > </ body > </ html > |
JS和CSS、IMAGES文件下载地址https://page69.ctfile.com/fs/3775069-203728262,自己根据html中的导入,找不到的在eclipse全局搜索
action代码:根据需求改地址
@RequestMapping(value="/add/{boxId}", method={RequestMethod.POST}) public void addPhotospost(@PathVariable(value="boxId") String boxId, HttpServletRequest request,HttpServletResponse response ) throws IOException { ServletContext servletContext=request.getSession().getServletContext(); String newFileName=""; PrintWriter out = response.getWriter(); //文件保存目录路径 String savePath = "E:/"; //String savePath = this.getServletContext().getRealPath("/") + configPath; // 临时文件目录 String tempPath = servletContext.getRealPath("/") + Constant.dirTemp; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); String ymd = sdf.format(new Date()); savePath += "/" + ymd + "/"; //创建文件夹 File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } tempPath += "/" + ymd + "/"; //创建临时文件夹 File dirTempFile = new File(tempPath); if (!dirTempFile.exists()) { dirTempFile.mkdirs(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(20 * 1024 * 1024); //设定使用内存超过5M时,将产生临时文件并存储于临时目录中。 factory.setRepository(new File(tempPath)); //设定存储临时文件的目录。 ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { List items = upload.parseRequest(request); System.out.println("items = " + items); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); String fileName = item.getName(); long fileSize = item.getSize(); if (!item.isFormField()) { String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; try{ File uploadedFile = new File(savePath, newFileName); OutputStream os = new FileOutputStream(uploadedFile); InputStream is = item.getInputStream(); byte buf[] = new byte[1024];//可以修改 1024 以提高读取速度 int length = 0; while( (length = is.read(buf)) > 0 ){ os.write(buf, 0, length); } //关闭流 os.flush(); os.close(); is.close(); System.out.println("上传成功!路径:"+savePath+"/"+newFileName); out.print(savePath+"/"+newFileName); }catch(Exception e){ e.printStackTrace(); } }else { String filedName = item.getFieldName(); System.out.println("==============="); System.out.println(new String(item.getString().getBytes("iso-8859-1"), "utf-8")); System.out.println("FieldName:"+filedName); // 获得裁剪部分的坐标和宽高 System.out.println("String:"+item.getString()); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.flush(); out.close(); }
效果图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?