上传文件和下载文件是个常用的技能,在哪里开发几乎都能遇见,而所有的上传控件各不相同,插件很多,后台也有很多,这里我只尝试过这个方法觉的还够简洁。具体如下实现:

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>&nbsp;&nbsp;&nbsp;
<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>
)

springMVC实现文件上传下载的更多相关文章

  1. SSM框架-SpringMVC 实例文件上传下载

    一.新建一个Web工程,导入相关的包 springmvc的包+commons-fileupload.jar+connom-io.jar+commons-logging,jar+jstl.jar+sta ...

  2. 14.SpringMVC之文件上传下载

    SpringMVC通过MultipartResolver(多部件解析器)对象实现对文件上传的支持. MultipartResolver是一个接口对象,需要通过它的实现类CommonsMultipart ...

  3. SpringMVC的文件上传下载,异常处理,拦截器的小总结

    文件的上传和下载 我们通常在访问网页时会使用到文件的上传与下载的功能,那么他是如何实现的呢? 1 下载: ResponseEntity :用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览 ...

  4. SpringMVC异步文件上传下载

    首先了解一下File的构造方法: File(String pathname):根据一个路径得到File对象 File(String parent,String child):根据一个目录和一个子文件/ ...

  5. SpringMVC文件上传下载(单文件、多文件)

    前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...

  6. SpringMVC文件上传下载

    在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...

  7. 使用springMVC实现文件上传和下载之环境配置与上传

    最近的项目中用到了文件的上传和下载功能,任务分配给了其他的同时完成.如今项目结束告一段落,我觉着这个功能比较重要,因此特意把它提取出来自己进行了尝试. 一. 基础配置: maven导包及配置pom.x ...

  8. SpringMVC 文件上传下载

    目录 文件上传 MultipartFile对象 文件下载 上传下载示例 pom.xml增加 创建uploadForm.jsp 创建uploadForm2.jsp 创建userInfo.jsp spri ...

  9. springmvc文件上传下载简单实现案例(ssm框架使用)

    springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...

随机推荐

  1. ThoughtWorks 面试

    ThoughtWorks 面试备忘录   ThoughtWorks 面试备忘录 前言 前段时间 ThoughtWorks 在网上和拉勾网合作搞了一次网络招聘,名为抛弃简历!让代码说话!可谓赚足了眼球, ...

  2. Prototype,创建型模式

    读书笔记_探索式测试_混合探索式测试   一.测试场景 1.讲述用户故事 2.描述需求 3.演示产品功能 4.演示集成场景 5.描述设置和安装 6.描述警告和出错情况 二.使用基于场景的探索式测试 1 ...

  3. WCF基于MSMQ的事件代理服务

    前言 公司目前楼主负责的项目正在改版升级,对之前的服务也在作调整,项目里有个操作日志的模块,就决定把日志单独提取出来,做个日志服务,所以就有了这篇文章 正文 MSMQ作为消息队列,B/S项目调用日志服 ...

  4. 生活沉思录 via 哲理小故事(四)

    1.围墙里的墓碑 第一次世界大战期间,驻守意大利某小镇的年轻军官结识了镇上的牧师.虽然军官信仰信教,而牧师是天主教牧师,但两人一见如故. 军官在一次执行任务中身负重伤,弥留之际嘱托牧师无论如何要把自己 ...

  5. 设计模式之观察者模式(Observable与Observer)

    设计模式之观察者模式(Observable与Observer) 好久没有写博客啦,之前看完了<设计模式之禅>也没有总结一下,现在回忆一下设计模式之观察者模式. 1.什么是观察者模式 简单情 ...

  6. Asycn/Await 异步编程初窥(二)

    经过总过4天的学习和实践,做完了 WinForm 下 .Net 4.5 的基本异步应用,实现了一个 Http 协议下载的测试程序,为以后使用 .Net 4.5 积累知识和经验.这个小程序完成这样几个作 ...

  7. MongoDB学习(翻译6)

    接上篇.... 字段或属性层次的序列化选项 有许多种让你控制序列化的方式,上一节通过约定方法来控制序列化,你也可以通过代码配置或者成员映射或者使用特性来控制你的序列化,下面说道的序列化的各个方面,我们 ...

  8. iOS蓝牙调用的一般流程

    一.服务端(也叫周边设备吧..脑残的翻译) 1.实现类必须遵守协议 CBPeripheralManagerDelegate 2.需要的主要类有: @property(strong,nonatomic) ...

  9. 使用Func<T1, T2, TResult>

    使用Func<T1, T2, TResult> 委托返回匿名对象   Func<T1, T2, TResult> 委托 封装一个具有两个参数并返回 TResult 参数指定的类 ...

  10. java自动生成略缩图

    当你要做一个图库的项目时,对图片大小.像素的控制是首先需要解决的难题. 本篇文章,在前辈的经验基础上,分别对单图生成略缩图和批量生成略缩图做个小结. 一.单图生成略缩图 单图经过重新绘制,生成新的图片 ...