上传文件和下载文件是个常用的技能,在哪里开发几乎都能遇见,而所有的上传控件各不相同,插件很多,后台也有很多,这里我只尝试过这个方法觉的还够简洁。具体如下实现:
1、spring-mvc.xml配置 添加如下,下划线的是关键
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:websocket="http://www.springframework.org/schema/websocket" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 自动扫描且只扫描@Controller --> <context:component-scan base-package="com.oasis.wyvern" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan> <context:annotation-config/> <context:component-scan base-package="com.oasis.wyvern.res.controller"/> <bean id="ignorTypeInfoJacksonAnnotationIntrospector" class="com.oasis.wyvern.res.utils.jackson.JsonMapper.IgnorTypeInfoJacksonAnnotationIntrospector"> </bean> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.fasterxml.jackson.databind.ObjectMapper"> <property name="serializationInclusion"> <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value> </property> <property name="annotationIntrospector" ref="ignorTypeInfoJacksonAnnotationIntrospector"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!--websocket 配置--> <bean id="websocket" class="com.oasis.wyvern.res.controller.websocket.WebsocketEndPoint"/> <websocket:handlers allowed-origins="*"> <websocket:mapping path="/websocket" handler="websocket"/> <websocket:handshake-interceptors> <bean class="com.oasis.wyvern.res.controller.websocket.HandshakeInterceptor"/> </websocket:handshake-interceptors> </websocket:handlers> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> <property name="maxUploadSize" value="104857600"/> <property name="maxInMemorySize" value="4096"/> </bean> <!-- 处理所有的无RequestMapping和静态内容的URL --> <mvc:default-servlet-handler/> <!-- 定义无需Controller的url<->view直接映射 --> <mvc:view-controller path="/core/404" view-name="/core/404"/> <mvc:view-controller path="/core/refresh" view-name="/core/refresh"/> <mvc:view-controller path="/core/error" view-name="/core/error"/> <!--<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.oasis.crm.controller.ziwei.core.formtoken.FormTokenInterceptor"/> </mvc:interceptor> </mvc:interceptors>--> <!-- Shiro 注解AOP --> <!-- Enable Shiro Annotations for Spring-configured beans. Only run after --> <!-- the lifecycleBeanProcessor has run: --> <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> </beans>
2、controller上传
/** * 创建文件 * @return */ @RequestMapping(CREATE) //ajax请求的url @ResponseBody public PackVo<Boolean> createAttachment(MultipartFile file ){ String uuid = UuidUtils.getUUID(); attachmentService.createAttachment(file,uuid); PackVo<Boolean> packVo = new PackVo<>(); packVo.setVo(Boolean.TRUE); packVo.setUdf2(uuid); return packVo; //controller返回值可看配置 可直接换为String }
3、文件上传后处理保存在服务器,或hbase
private Attachment generateAttachment(MultipartFile file, String uuid) throws IllegalStateException, IOException { Calendar calendar = Calendar.getInstance(); String toMonth = DateUtil.dateFormat(calendar.getTime(), "yyyyMM"); String toDay = DateUtil.dateFormat(calendar.getTime(), "yyyyMMdd"); toDay = toDay.substring(6); String path = "d:/attachment/" + toMonth + "/" + toDay + "/"; String myFileName = file.getOriginalFilename(); // String noPostfixFileName = myFileName.substring(0,myFileName.indexOf(".")); FileManageUtil.makeDirectory(path); path += myFileName; File localFile = new File(path); file.transferTo(localFile); Attachment attachment = new Attachment(); attachment.setName(myFileName); attachment.setAttachmentUrl(path); attachment.setFileSize(Float.parseFloat(file.getSize()+"")); attachment.setUuid(uuid); return attachment; }
二、1、文件下载
@RequestMapping(value=DOWNLOAD) public ResponseEntity<byte[]> testResponseEntity(String realName,String path) throws IOException { byte[] body = null; File f = new File(path); InputStream in = new FileInputStream(f); body = new byte[in.available()]; in.read(body); in.close(); HttpHeaders headers = new HttpHeaders(); //响应头的名字和响应头的值 headers.add("Content-Disposition", "attachment;filename="+new String(realName.getBytes("UTF-8"),"iso-8859-1"));//解决文名称中文乱码 HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode); return response; }
2、前台实现下载,上传就略去了,reactjs写法
return ( <div> { this.state.initialObj.attachmentVoList.map((attachment)=> { return ( <div key={attachment.id} className="attachment-list"> <a>{attachment.name} </a> <a href={Remote.cert.download+'?path='+attachment.attachmentUrl+'&realName='+attachment.name} >下载 </a> <span className="ant-divider" /> <Popconfirm title="您确定删除吗?" onConfirm={this.deleteData.bind(this, attachment.id)}> <a >删除</a> </Popconfirm> </div> ) }) } </div> )