上傳文件和下載文件是個經常使用的技能,在哪裏開發幾乎都能碰見,而全部的上傳控件各不相同,插件不少,後臺也有不少,這裏我只嘗試過這個方法覺的還夠簡潔。具體以下實現:react
一、spring-mvc.xml配置 添加以下,下劃線的是關鍵web
<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>
二、controller上傳 ajax
/** * 建立文件 * @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 }
三、文件上傳後處理保存在服務器,或hbasespring
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; }
2、一、文件下載express
@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; }
二、前臺實現下載,上傳就略去了,reactjs寫法apache
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> )