SpringMVC中文件的上传下载

SpringMVC中文件的上传下载

文件下载

1.将控制器方法返回值设置为ResponseEntity

2.在控制器方法内部获取到文件的真实路径并且使用IO流读取文件到字节数组

3.创建HttpHeads对象添加请求头属性

​ 属性为:Content-Disposition 值为attachment;filename=1.jpg //attachment是用附件的方式进行下载 filename是下载使用的文件名

4.使用文件字节数组,HttpHeads和HttpStatus枚举来创建ResponseEntity来返回

代码如下:

@Controller
public class FileController {

    @RequestMapping("/filedownload")
    public ResponseEntity downloadImg(HttpSession session) throws IOException {
        //获取上下文
        ServletContext servletContext = session.getServletContext();
        //将工程中的文件路径转换为真实路径给IO流api使用
        String realPath = servletContext.getRealPath("/static/img/1.jpg");
        FileInputStream fileInputStream = new FileInputStream(realPath);
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);

        //创建响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition","attachment;filename=1.jpg");
        HttpStatus ok = HttpStatus.OK;
        //使用图片字节数组 请求头和状态码创建响应报文对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, ok);
        return  responseEntity;

    }
}

文件上传

前端上传要求

​ 必须使用post方式来提交数据 //get方式是将请求体参数拼接在地址栏,很明显文件上传无法做到

​ 必须使用enctype来指定请求体数据格式且格式必须为multipart/form-data//enctype默认application/x-www-form-urlencoded,默认值的作用是将以字符串的形式来发送数据,而multipart/form-data图片非文本文件可以以二进制的数据发送到服务端

1.导入文件上传依赖

 <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
</dependency>

2.配置上传文件解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

3.在控制器的方法中写入MultipartFile形参,这样文件上传解析器就可以将上传的文件封装成对象给我们使用

 @RequestMapping("/upload")
    @ResponseBody
    public String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        //获取文件名
        String originalFilename = file.getOriginalFilename();//获取文件名
        String realPath = request.getServletContext().getRealPath("/static/img");
        file.transferTo(new File(realPath+File.separator+originalFilename));
        return "success";
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
当使用Spring MVC进行文件上传时,需要注意以下几点: 1. 首先,在Spring MVC配置文件启用multipart解析器。可以通过在servlet-context.xml或applicationContext.xml文件添加以下配置来完成: ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <context:component-scan base-package="com.example" /> <mvc:annotation-driven /> <!-- 配置multipart解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10000000"/> </bean> </beans> ``` 这里我们使用了CommonsMultipartResolver类来处理文件上传,还可以通过maxUploadSize属性设置上传文件的最大大小。 2. 在Controller编写处理文件上传的方法,并使用@RequestParam注释来接收上传的文件。例如: ```java @RequestMapping(value="/upload", method=RequestMethod.POST) public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // 文件上传逻辑处理 } catch (Exception e) { e.printStackTrace(); } } return "redirect:/successUrl"; } ``` 在上面的代码,我们使用@RequestParam注释将上传的文件绑定到MultipartFile对象,并使用getBytes()方法获取文件内容。 3. 最后,在表单添加文件上传控件,并指定form的enctype属性为“multipart/form-data”。例如: ```html <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上传" /> </form> ``` 这样就完成了文件上传的全部过程。注意,在实际应用,还需要对上传的文件进行安全检查,例如检查文件类型、文件大小等,以确保应用的安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吹不断的Spring

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值