ssm框架Springmvc文件上传实现代码详解

时间:2021-05-19

一、上传:

1)编写前台文件上传表单。Method必须为post,enctype为mutipart/form-data

<body><%--文件上传 1)method必须指定为post 2)enctype必须指定为multipart/form-data--%><h1>头像上传</h1><form action="${pageContext.request.contextPath}/admin/headpic" method="post" enctype="multipart/form-data"> 选择头像:<input type="file" name="headpic"/><%-- ${param.属性值}==request.getParameter(属性值)--%> <input type="text" name="id" value="${param.id}"> <input type="submit" value="上传"/></form></body>

2)编写控制层代码,获取上传的文件数据,并保存MultipartFile;

//MultipartFile:用来接收上传的文件,参数名与input的name一直 //@SessionAttribute("admin"):获取session域中的值 //@RequestParam(required = false):指定对应的参数可以为空,不是必须有值 @RequestMapping("/headpic") public String headPic(MultipartFile headpic,@RequestParam(required = false) Admin admin,Integer id) throws IOException { String filename = headpic.getOriginalFilename(); System.out.println("上传的文件名:"+filename); File file=new File("E:/headpic/"+filename); if (!file.getParentFile().exists()){ file.getParentFile().mkdirs();//如果父目录不存在,创建该目录 } //保存文件,将上传的文件内容写入file headpic.transferTo(file); admin=new Admin(id); //将头像访问路径保存到对象中 admin.setHeadpic("/head/"+filename); //更新用户头像信息 adminService.updateHeadPic(admin); return "redirect:list"; }

3)在springmvc配置文件中配置文件上传配置项。配置multipartResolver;

<!--配置文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--设置文件编码格式--> <property name="defaultEncoding" value="UTF-8"/> <!--设置最大上传大小--> <property name="maxUploadSize" value="10240000" /> </bean><!-- 资源映射,将请求地址映射到某个目录或具体的磁盘路径 mapping:配置请求地址; location:配置文件路径 请求地址:/head/logo.png==>E:/headpic/logo.png--> <mvc:resources mapping="/head/**" location="file:E:/headpic/"></mvc:resources><!-- 请求地址为/headimg/logo.png==>/WEB-INF/img/logo.png--> <mvc:resources mapping="/headimg/**" location="/WEB-INF/img/"></mvc:resources>

二、下载:

1) 获取到下载文件的路径;

2) 读取文件内容到字节数组;

3) 返回字节数组,并声明返回类型为stream,设置附件名称;

@GetMapping("/headPicDownload") public ResponseEntity<byte[]> headPicDownload(String filename) throws IOException { //1、定位到文件地址 File file=new File("E:/headpic/"+filename); //2、读取文件内容 byte[] bytes= FileUtils.readFileToByteArray(file); //3、设置http响应头 HttpHeaders headers = new HttpHeaders(); //设置ContentType为stream headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //4、设置以附件形式打开 headers.setContentDispositionFormData("attachment",filename); // 内容 头部信息 http状态码 return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.CREATED); }<td> <img style="width: 25px;height: 25px;border-radius: 50%;" src="${pageContext.request.contextPath}${admin.headpic}"/> <a href="${pageContext.request.contextPath}/admin/headPicDownload?filename=${fn:replace(admin.headpic," rel="external nofollow" /head/","" )}">下载</a> </td>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章