注释当中加的很详细,这里把其他关联的代码一并贴出,仅供参照。
debug : function(msg) { if (this._set.debug) { if (typeof (console) != "undefined") console.log(msg); else alert(msg); } }, jsonEval : function(data) { try { if ($.type(data) == 'string') return eval('(' + data + ')'); else return data; } catch (e) { return {}; } }, ajaxError : function(xhr, ajaxOptions, thrownError) { if (xhr.responseText) { $.showErr("<div>" + xhr.responseText + "</div>"); } else { $.showErr("<div>Http status: " + xhr.status + " " + xhr.statusText + "</div>" + "<div>ajaxOptions: " + ajaxOptions + "</div>" + "<div>thrownError: " + thrownError + "</div>"); } }, ajaxDone : function(json) { if (json[YUNM.keys.statusCode] == YUNM.statusCode.error) { if (json[YUNM.keys.message]) { YUNM.debug(json[YUNM.keys.message]); $.showErr(json[YUNM.keys.message]); } } else if (json[YUNM.keys.statusCode] == YUNM.statusCode.timeout) { YUNM.debug(json[YUNM.keys.message]); $.showErr(json[YUNM.keys.message] || YUNM.msg("sessionTimout"), YUNM.loadLogin); } },
####2、后端springMVC文件保存
#####2.1、为springMVC增加文件的配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8"> <property name="maxUploadSize" value="1024000000"></property> </bean> <mvc:annotation-driven conversion-service="conversionService" /> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <!-- 这里使用string to date可以将dao在jsp到controller转换的时候直接将string格式的日期转换为date类型 --> <bean class="com.honzh.common.plugin.StringToDateConverter" /> <!-- 为type为file类型的数据模型增加转换器 --> <bean class="com.honzh.common.plugin.CommonsMultipartFileToString" /> </list> </property> </bean>
这里就不做过多介绍了,可参照我之前写的SpringMVC之context-dispatcher.xml,了解基本的控制器
#####2.2、FileController.java
package com.honzh.spring.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.honzh.common.base.UploadFile; import com.honzh.spring.service.FileService; @Controller @RequestMapping(value = "/file") public class FileController extends BaseController { private static Logger logger = Logger.getLogger(FileController.class); @Autowired private FileService fileService; @RequestMapping("") public void index(HttpServletRequest request, HttpServletResponse response) { logger.debug("获取上传文件..."); try { UploadFile uploadFiles = fileService.saveFile(request); renderJsonDone(response, uploadFiles); } catch (Exception e) { logger.error(e.getMessage()); logger.error(e.getMessage(), e); renderJsonError(response, "文件上传失败"); } } }
#####2.3、FileService.java
package com.honzh.spring.service; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Random; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.honzh.common.Variables; import com.honzh.common.base.UploadFile; import com.honzh.common.util.DateUtil; @Service public class FileService { private static Logger logger = Logger.getLogger(FileService.class); public UploadFile saveFile(HttpServletRequest request) throws IOException { logger.debug("获取上传文件..."); // 转换为文件类型的request MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 获取对应file对象 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); Iterator<String> fileIterator = multipartRequest.getFileNames(); // 获取项目的相对路径(http://localhost:8080/file) String requestURL = request.getRequestURL().toString(); String prePath = requestURL.substring(0, requestURL.indexOf(Variables.ctx)); while (fileIterator.hasNext()) { String fileKey = fileIterator.next(); logger.debug("文件名为:" + fileKey); // 获取对应文件 MultipartFile multipartFile = fileMap.get(fileKey); if (multipartFile.getSize() != 0L) { validateImage(multipartFile); // 调用saveImage方法保存 UploadFile file = saveImage(multipartFile); file.setPrePath(prePath); return file; } } return null; } private UploadFile saveImage(MultipartFile image) throws IOException { String originalFilename = image.getOriginalFilename(); logger.debug("文件原始名称为:" + originalFilename); String contentType = image.getContentType(); String type = contentType.substring(contentType.indexOf("/") + 1); String fileName = DateUtil.getCurrentMillStr() + new Random().nextInt(100) + "." + type; // 封装了一个简单的file对象,增加了几个属性 UploadFile file = new UploadFile(Variables.save_directory, fileName); file.setContentType(contentType); logger.debug("文件保存路径:" + file.getSaveDirectory()); // 通过org.apache.commons.io.FileUtils的writeByteArrayToFile对图片进行保存 FileUtils.writeByteArrayToFile(file.getFile(), image.getBytes()); return file; } private void validateImage(MultipartFile image) { } }
#####2.4、UploadFile.java
package com.honzh.common.base; import java.io.File; import com.honzh.common.Variables; public class UploadFile { private String saveDirectory; private String fileName; private String contentType; private String prePath; private String completeSavePath; private String relativeSavePath; public UploadFile(String saveDirectory, String filesystemName) { this.saveDirectory = saveDirectory; this.fileName = filesystemName; } public String getFileName() { return fileName; } public String getSaveDirectory() { return saveDirectory; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getPrePath() { if (prePath == null) { return ""; } return prePath; } public void setPrePath(String prePath) { this.prePath = prePath; setCompleteSavePath(prePath + getRelativeSavePath()); } public String getCompleteSavePath() { return completeSavePath; } public void setCompleteSavePath(String completeSavePath) { this.completeSavePath = completeSavePath; } public String getRelativeSavePath() { return relativeSavePath; } public void setRelativeSavePath(String relativeSavePath) { this.relativeSavePath = relativeSavePath; } public void setSaveDirectory(String saveDirectory) { this.saveDirectory = saveDirectory; } public void setFileName(String fileName) { this.fileName = fileName; } public File getFile() { if (getSaveDirectory() == null || getFileName() == null) { return null; } else { setRelativeSavePath(Variables.ctx + "/" + Variables.upload + "/" + getFileName()); return new File(getSaveDirectory() + "/" + getFileName()); } } }