/**************************************************************************************工具类********************************************************************************************************/ package com.zero4j.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.MultipartFile; /** * * 上传工具类 * * */ @Component public class UploadUtil implements ServletContextAware { private static ServletContext servletContext = null; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } /** * 保存文件 * * @param files * @param id * @param request * @author hzr 2016年12月5日 */ public static void fileSave(MultipartFile files, String id, HttpServletRequest request) { String fileFileName = files.getOriginalFilename(); if (files == null || files.equals("")) { return; } else { String extension = (fileFileName.substring(fileFileName.lastIndexOf(".") + 1, fileFileName.length())).toLowerCase(); // 获取扩展名并转换成小写 // 开始执行上传操作 try { // 设定图片上传的临时目录 File srcFile = new File(servletContext.getRealPath("/uploads/other/"), id + "." + extension); System.out.println(srcFile); if (!srcFile.exists()) { System.out.println("路径不存在!!!!!!!!"); srcFile.mkdirs(); } files.transferTo(srcFile); } catch (Exception e) { e.printStackTrace(); return; } /* * //如果文件后缀不同则先删除原有文件 * if(files.getExtension()==null||!extension.equals * (_upload.getExtension().toLowerCase())){ new * File(ServletActionContext * .getRequest().getRealPath("/uploads/other"), * _upload.getId()+"."+_upload.getExtension()).deleteOnExit(); } * * //更新文件后缀到数据库中 _upload.setContentType(this.fileContentType); * _upload.setExtension(extension); * this.uploadService.update(_upload); */ // } } } /** * 保存文件 * * @param files * @param id * @param request * @author hzr 2016年12月5日 */ public static String fileSave_other(MultipartFile files, String id, HttpServletRequest request) { String fileFileName = files.getOriginalFilename(); if (files == null || files.equals("")) { return null; } else { String extension = (fileFileName.substring(fileFileName.lastIndexOf(".") + 1, fileFileName.length())).toLowerCase(); // 获取扩展名并转换成小写 // 开始执行上传操作 try { // 设定图片上传的临时目录 File srcFile = new File(servletContext.getRealPath("/uploads/styleItem/"), id + "." + extension); System.out.println(srcFile); if (!srcFile.exists()) { System.out.println("文件路径不存在!!!!!!!!"); srcFile.mkdirs(); } /*String imageSourcePath = request.getRealPath("/uploads/styleItem"); File srcFile = new File(imageSourcePath, id + "." + extension); if(!srcFile.exists()){ srcFile.mkdir(); }*/ //System.out.println(srcFile.toString()+"路径asdasdasdsa"); files.transferTo(srcFile); return "/uploads/styleItem/"+id + "." + extension ; } catch (Exception e) { e.printStackTrace(); return null ; } /* * //如果文件后缀不同则先删除原有文件 * if(files.getExtension()==null||!extension.equals * (_upload.getExtension().toLowerCase())){ new * File(ServletActionContext * .getRequest().getRealPath("/uploads/other"), * _upload.getId()+"."+_upload.getExtension()).deleteOnExit(); } * * //更新文件后缀到数据库中 _upload.setContentType(this.fileContentType); * _upload.setExtension(extension); * this.uploadService.update(_upload); */ // } } } /** * 删除文件夹 * @param filePathAndName String 文件夹路径及名称 如c:/fqf * @param fileContent String * @return boolean */ public static void delFolder(String folderPath) { folderPath=servletContext.getRealPath(folderPath); //System.out.println("执行删除文件夹操作 源文件路径"+folderPath); try { delAllFile(folderPath); //删除完里面所有内容 String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); //删除空文件夹 } catch (Exception e) { System.out.println("删除文件夹操作出错"); e.printStackTrace(); } } /** * 删除文件夹里面的所有文件 * @param path String 文件夹路径 如 c:/fqf */ public static void delAllFile(String path) { path=servletContext.getRealPath(path); File file = new File(path); if (!file.exists()) { return; } if (!file.isDirectory()) { return; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件 delFolder(path+"/"+ tempList[i]);//再删除空文件夹 } } } /** * 复制单个文件 * @param oldPath String 原文件相对路径 如:c:/fqf.txt * @param newPath String 复制后相对路径 如:f:/fqf.txt * @return boolean */ public static boolean copyFile(String oldPath, String newPath) { // System.out.println("执行复制文件操作 源文件路径"+servletContext.getRealPath(oldPath)+" 目的文件路径 "+servletContext.getRealPath(newPath)); try { // int bytesum = 0; int byteread = 0; File oldfile = new File(servletContext.getRealPath(oldPath)); File srcFile = new File(servletContext.getRealPath("/uploads/styleItemTemplate/")); //System.out.println(srcFile); if (!srcFile.exists()) { System.out.println("文件夹路径不存在!!!!!!!!"); srcFile.mkdirs(); } File myFileName = new File(servletContext.getRealPath(newPath)); try{ if (!myFileName.exists()) { myFileName.createNewFile(); } }catch (Exception e) { System.out.println("新建文件操作出错"); e.printStackTrace(); return false; } if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(servletContext.getRealPath(oldPath)); //读入原文件 FileOutputStream fs = new FileOutputStream(servletContext.getRealPath(newPath)); byte[] buffer = new byte[1444]; // int length; while ( (byteread = inStream.read(buffer)) != -1) { // bytesum += byteread; //字节数 文件大小 // System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); fs.close(); // System.out.println("复制成功"); } return true; } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); return false; } } /** * 复制单个文件 * @param tempalteFileFolderRoute String 临时文件夹路径相对路径 如:c:/fqf * @param newPath String 资源文件夹路径相对路径 如:f:/fqf1 * @return boolean */ public static boolean copyFileFolder(String tempalteFileFolderRoute, String newPath) { // System.out.println("执行复制文件操作 源文件路径"+servletContext.getRealPath(oldPath)+" 目的文件路径 "+servletContext.getRealPath(newPath)); try { File srcFile = new File(servletContext.getRealPath(tempalteFileFolderRoute)); if (!srcFile.exists()) { System.out.println("文件夹路径不存在!!!!!!!!"); srcFile.mkdirs(); } File srcFile1 = new File(servletContext.getRealPath(newPath)); if (!srcFile1.exists()) { System.out.println("文件夹路径不存在!!!!!!!!"); srcFile1.mkdirs(); } String path=servletContext.getRealPath(tempalteFileFolderRoute); File file = new File(path); String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { String tempRoute=tempalteFileFolderRoute+"/"+tempList[i]; String normalRoute=newPath+"/"+tempList[i]; File oldfile = new File(servletContext.getRealPath(tempRoute)); File myFileName = new File(servletContext.getRealPath(normalRoute)); int byteread = 0; try{ if (!myFileName.exists()) { myFileName.createNewFile(); } }catch (Exception e) { System.out.println("新建文件操作出错"); e.printStackTrace(); return false; } if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(servletContext.getRealPath(tempRoute)); //读入原文件 FileOutputStream fs = new FileOutputStream(servletContext.getRealPath(normalRoute)); byte[] buffer = new byte[1444]; // int length; while ( (byteread = inStream.read(buffer)) != -1) { // bytesum += byteread; //字节数 文件大小 // System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); //System.out.println("复制成功"); } } return true; } catch (Exception e) { System.out.println("复制文件操作出错"); e.printStackTrace(); return false; } } /*para source 源文件目录 dest 复制文件目录 para*/ /*复制文件*/ public static void copyFile2(String source, String dest) { System.out.println("执行复制文件操作 源文件路径"+servletContext.getRealPath(source)+" 目的文件路径 "+servletContext.getRealPath(dest)); File srcFile = new File(servletContext.getRealPath("/uploads/styleItemTemplate")); System.out.println(srcFile); if (!srcFile.exists()) { System.out.println(servletContext.getRealPath(dest)+" 路径不存在!!!!!!!!"); srcFile.mkdirs(); } try { File in = new File(servletContext.getRealPath(source));//源文件目录 File out = new File(servletContext.getRealPath(dest)); //复制文件目录 FileInputStream inFile = new FileInputStream(in); FileOutputStream outFile = new FileOutputStream(out); byte[] buffer = new byte[102400]; int i = 0; while ((i = inFile.read(buffer)) != -1) { outFile.write(buffer, 0, i); }//end while inFile.close(); outFile.close(); System.out.println("复制成功"); }//end try catch (Exception e) { System.out.println(e.toString()); }//end catch }//end copyFile /*删除文件方法*/ public boolean deleteFile(String sPath) { System.out.println("执行删除文件操作 源文件路径"+servletContext.getRealPath("/uploads/styleItem")+sPath); boolean flag = false; File file = new File(servletContext.getRealPath("/uploads/styleItem")+sPath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } } /************************************************************************调用*****************************************************************************/ @RequestParam MultipartFile[] imgRoute uuid-->file name UploadUtil.fileSave_other(uploadFiles[k], uuid, request); /*************************************************************************************前端 代码**************************************************************************************/ /**********************************************************jsp**************************************************************/ <input type="file" name="imgRoute" class="fileRouteIn" value="" style="200px; display:inline;" required="required" /> /******************************************************************************js*************************************************************************/ /* 发送上传文件请求 para--uploadFiles 选择文件 fileRouteIn--name para--num 选择文件 fileRouteIn--index序号 */ function uploadFile(uploadFiles, num) { // alert(num); $(".fileRouteIn:eq(" + num + ")").text( $(".fileRouteIn:eq(" + num + ")").val()); var token = $.cookie("token"); $.ajaxFileUpload({ url : "api/v1/styleItems/uploadFile?token=" + token, type : "POST", secureuri : false, fileElementId : uploadFiles,//该参数名要与input【type=‘file’】 的name相同 dataType : "json", success : function(response) { if (response.status == 200) { blackDialog.show(response.uploadFileRoute); var valueaa = response.uploadFileRoute; $(".fileRouteIn:eq(" + num + ")").attr("value", response.uploadFileRoute); $(".viewMessege:eq(" + num + ")").text("所选文件上传成功"); console.log(valueaa + "213123"); blackDialog.show(response.message); $(".processbar:eq(" + num + ")").width("95%"); } else { window.clearInterval(bartimer); $(".processbar:eq(" + num + ")").width("0%"); $(".processbar:eq(" + num + ")").text(0 + "%"); $(".viewMessege:eq(" + num + ")").text("文件上传失败"); blackDialog.show(response.message); } } }); }