最近实现了文件上传的功能,是基于spring +struts+jquery实现的。
需要注意的是 前台要引用jquery的 ajaxfileupload.js 文件。
具体伪代码如下:
1,控制层.
我们提供了一个基类定义了一个文件上传的基本设置,比如控键名和上传路径等,如何想要特别处理,需要子类继承 UploadFileCallback,实现callback 方法。
下面代码是我整合后的基类和实现类在一起后的效果。
public class UploadAction extends ActionSupport implements Preparable, ModelDriven, UploadFileCallback{ public static String UPLOADFRONTENDBASEPATH = "/home/upload"; static { //the path of upload file UPLOADFRONTENDBASEPATH = SettingManager.getInstance().getConfig().getString("uploadfrontEndBasePath"); } private File[] uploadFile; private String[] uploadFileFileName; private static final String[] imageSuffix = {".jpg",".JPG",".jpeg",".JPEG",".gif",".GIF",".png",".PNG",".bmp",".BMP",".ico",".ICO"}; public String[] processUploadFile() { if (uploadFile != null) { String suffix = uploadFileFileName[0].substring(uploadFileFileName[0].lastIndexOf(".")); Arrays.sort(imageSuffix); int result = Arrays.binarySearch(imageSuffix, suffix); // 在数组中搜索是否含有该后缀名 if (result < 0) { // 如果不包含,返回特殊值 return new String[] { "FORMAT_ERROR" }; } int fileCounts = uploadFile.length; logger.debug("UploadFile counts :" + fileCounts); // 按照File[]的长度初始化一个用于返回文件上传结果的String数组,这个数组的元素与File[]的元素一一对应 String[] uploadFileResult = new String[fileCounts]; // 判断子类是否实现了UploadFileCallback接口,如果实现了该接口,文件处理逻辑移交到子类实现. if (this instanceof UploadFileCallback) { UploadFileCallback callback = (UploadFileCallback) this; for (int i = 0; i < this.uploadFile.length; i++) { uploadFileResult[i] = callback.callback(this.uploadFile[i], this.uploadFileFileName[i]); } } else { // 子类没有实现UploadFileCallback接口,采用默认的文件处理方式:将上传的文件保存到应用的files目录中. String appDir = this.getRequest().getSession() .getServletContext() .getRealPath(DEFAULT_UPLOAD_FILE_DIR) + File.separator; File dir = new File(appDir); if (!dir.exists()) { dir.mkdir(); } for (int i = 0; i < this.uploadFile.length; i++) { String filePath = appDir + this.uploadFileFileName[i]; try { // 把临时文件复制到目标路径下 FileUtils.copyFile(this.uploadFile[i], new File( filePath)); // 文件地址作为上传结果返回 uploadFileResult[i] = filePath; } catch (IOException e) { e.printStackTrace(); } } } return uploadFileResult; } else { return null; } } public File[] getUploadFile() { return uploadFile; } public void setUploadFile(File[] uploadFile) { this.uploadFile = uploadFile; } public String[] getUploadFileFileName() { return uploadFileFileName; } public void setUploadFileFileName(String[] uploadFileFileName) { this.uploadFileFileName = uploadFileFileName; } /** * 图片上传回调函数 */ @Override public String callback(File uploadFile, String uploadFileFileName) { String suffix = uploadFileFileName.substring(uploadFileFileName.lastIndexOf(".")); uploadFileFileName =generateFileName(suffix); //BACK GROUND String appDir = getFeedbackPath(BASEPATH); String filePath = appDir + uploadFileFileName; File old = new File(filePath); if(old.exists()){ old.delete(); } try { // 把临时文件复制到目标路径下(同时备份) FileUtils.copyFile(uploadFile,new File(URLDecoder.decode(filePath, "UTF-8"))); //如果前后台部署在二个tomcat下面,那么图片则同时复制一份。 if(!UPLOADFRONTENDBASEPATH.equals(BASEPATH)){ //FRONT END String frontDir = getFeedbackPath(UPLOADFRONTENDBASEPATH); String frontFilePath = frontDir + uploadFileFileName; File frontOld = new File(frontFilePath); if(frontOld.exists()){ frontOld.delete(); } // 把临时文件复制到目标路径下(同时备份) FileUtils.copyFile(uploadFile,new File(URLDecoder.decode(frontFilePath, "UTF-8"))); } } catch (IOException e) { e.printStackTrace(); } return uploadFileFileName; } // 存放图片地址 public String getFeedbackPath(String basepath) { String realPath = basepath + File.separator+"feedbackPic" + File.separator; File dir = new File(realPath); if (!dir.exists()) { dir.mkdir(); } return realPath; } private String generateFileName(String fileName) { DateFormat format = new SimpleDateFormat("yyMMddHHmmss"); String formatDate = format.format(new Date()); int random = new Random().nextInt(10000); int position = fileName.lastIndexOf("."); String extension = fileName.substring(position); return formatDate + random + extension; } /** * * @return */ public String ajaxUploadFiles(){ Map<String, Object> result = new HashMap<String, Object>(); String[] files= processUploadFile(); if(files != null && files.length>0){ if("FORMAT_ERROR".equals(files[0])){ result.put("isSuccess", false); }else{ result.put("filePath", files[0]); result.put("isSuccess", true); } } this.getRequest().setAttribute(GsonResult.GSON_RESULT_OBJECT, result); return "ajax"; } }
2. jsp 界面
我采用的是ajax处理图片上传。 上传控键名为uploadFile。
<!-- js reference--> <script type="text/javascript" src="scripts/jquery/ajaxfileupload.js"></script> <script type="text/javascript" src="scripts/jquery/jquery1.7.js"></script> <div> <a href="javascript:addImgAttachment();" id="staffInfo_add"> <i class="ydicons ydicons-feedbackAttach"></i> 添加附件 </a> <input class="" id="uploadFile" name="uploadFile" type="file" accept="image/*" onchange="uploaderImg();" style="display:none;"> </div> <script type="text/javascript"> function uploaderImg() { $.ajaxFileUpload({ url : "${ctx}/ss/ssAjax/Upload/ajaxUploadFiles.do", //上传文件的服务端 secureuri : false, //是否启用安全提交 dataType : "json", //数据类型 fileElementId : "uploadFile", //表示文件域ID success : function(data) {//提交成功后处理函数 html为返回值,status为执行的状态 if (data.isSuccess) { //上传成功后处理 } }, error : function(data, status, e) {//提交失败处理函数 alert("上传失败!" + e); } }); } </script>