Spring实现文件的上传和下载

Spring实现文件的上传

第一种方法:
  • 我们经常能在一个网页中见到让你上传文件的例子吧,比如你在提交简历的时候,就需要把那个简历传递给对方,那么到底是怎么实现的呢?下面我们来看看。
  1. 首先表单为例可以提交成功,需要用post进行提交,并且设置表单的 ectype;
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<body>
<form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/file/upload">
	<!--设置输入框的name,以便于后台可以获取到 -->
    <input type="file" name="file">
    <input type="submit" name="upLoad">
</form>
</body>
</html>

  1. 接下来,编辑我们的spring配置文件;
<?xml version="1.0" encoding="UTF-8"?>

<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描注解-->
    <context:component-scan base-package="com.baidu.controller"/>
    <!--加载驱动-->
    <mvc:annotation-driven/>
    <!--静态资源过滤器-->
    <mvc:default-servlet-handler/>
    <!-- 多部分文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600" />
        <property name="maxInMemorySize" value="4096" />
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
</beans>
  1. 编写controller层

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
@RequestMapping("/file")
public class UploadController {
	//设置字符编码,防止乱码
    @RequestMapping(value = "/upload",produces = "application/json;charset = utf-8")    @ResponseBody
    public String upload(@RequestParam ("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        String filename = file.getOriginalFilename();
        if ("".equals(filename)){
            return "redirect:/index.jsp";
        }

        System.out.println("上传文件名:"+ filename);
        String path = request.getServletContext().getRealPath("/upload");
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdir();
        }
        System.out.println("文件上传保存地址:"+ file1);
        InputStream is = file.getInputStream();
        // 我这里上传到了target目录下的uoload文件夹中
        OutputStream os = new FileOutputStream(new File(file1,filename));
        int len = 0;
        byte []b = new byte[1024];
        while ((len = is.read(b)) != -1){
            os.write(b,0,len);
            os.flush();
        }
        os.close();
        is.close();
        return "文件上传成功!";
    }
}
第二种方法:

前端页面不变,只需要改controller层代码即可。


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file2")
public class FileUploadController {
    @RequestMapping(value = "/upload",produces = "application/json;charset = utf-8")
    @ResponseBody
    public String upload2(@RequestParam ("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String path = request.getServletContext().getRealPath("/upload");
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdir();
        }
        System.out.println(file1);
        file.transferTo(new File(file1 + "/" + file.getOriginalFilename()));
        return "上传完毕!";
    }
}

SpringMVC实现文件下载
  1. 首选编写前端页面
<p><a href="${pageContext.request.contextPath}/download">下载图片</a></p>
  1. 编写controller层代码
 @RequestMapping(value = "/download",produces = "application/json;charset = utf-8")
    @ResponseBody
    public String download(HttpServletResponse response) throws IOException {
        //要下载的图片地址
        System.out.println("hahaha");
        String path = "C:/Users/35158/Desktop/";
        String fileName = "1.jpg";
        File file = new File(path,fileName);
        //设置响应头的信息
        response.reset();//让页面不缓存
        response.setCharacterEncoding("utf-8");
        //二进制流传输数据
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));

        FileInputStream is = new FileInputStream(file);
        ServletOutputStream os = response.getOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1){
            os.write(buffer,0,len);
            os.flush();
        }
        os.close();
        is.close();
        return null;
    }
  1. OK,去到Tomcat跑一下;
    在这里插入图片描述
  2. 点击下载图片
    在这里插入图片描述
  3. 去到我们下载之后的路径找一下
    在这里插入图片描述
  4. OK,找到了。下载成功!
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值