springmvc文件的上传与下载

1springmvc的依赖

 <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
      <exclusions>
        <exclusion>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>

web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!-- 编码格式过滤 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern> / *</url-pattern>
  </filter-mapping>

<servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
  </init-param>
</servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

springmvc.xml

<?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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.qf"/>

    <mvc:annotation-driven/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/view/"/>
        <property name="suffix" value=".html"/>
    </bean>

    <!--        配置文件上传-->
    <!-- 文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 允许最大上传大小 -->
        <property name="maxUploadSize" value="10240000"/>
    </bean>
</beans>

平常前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<button id="btn1">点击</button>
<button id="btn2">点击</button>

<script src="/js/jquery-2.1.0.js"></script>

<script>
        $("#btn1").click(function (){
            $.ajax({
                url:"/test4.do",
                type:"get",
                data:{"id":1,"username":"张三"},
                success:function (ret){
                    if (ret.code == 0){
                        alert(ret.msg)
                    }
                },
                error:function (){
                    alert("服务器正忙!")
                }
            })
        });
        $("#btn2").click(function (){
            $.ajax({
                url:"/test5.do",
                type:"get",
                data:{"id":1,"username":"张三","score":99.9,"birthday":"2023-10-13"},
                contentType:"application/json",
                success:function (ret){
                    if (ret.code == 0){
                        alert(ret.msg)
                    }
                },
                error:function (){
                    alert("服务器正忙!")
                }
            })
        });
</script>
</body>
</html>

后端

@Controller
public class MyController {

    @RequestMapping("/test2")
    @ResponseBody
    public ResultData tset2(){
        System.out.println("true = ");
        ResultData resultData = new ResultData();
        return resultData.ok();
    }
    @RequestMapping("/test1")
     @ResponseBody
    public String test1() {
        System.out.println("响应json-test1" );
        return "{\"code\":200,\"msg\":\"OK\"}";
    }
    @RequestMapping("/test")
    @ResponseBody
    public ResultData tset(){
        System.out.println("响应json-test");
        List<User> list = new ArrayList<>();
        for (int i = 0; i <10 ; i++) {
            User user = new User();
            user.setId(i);
            user.setUsername("姓名"+i+"号");
            user.setBirthday(new Date(i*60));
            user.setScore(i*33.3);
            list.add(user);
        }
        ResultData resultData = new ResultData();
        return resultData.ok(list);
    }
 @RequestMapping("/test4")
    public ResultData test4(int id,String username){
        System.out.println("id = " + id);
        System.out.println("username = " + username);
        return ResultData.ok();
    }

    @RequestMapping("/test5")

    public ResultData test5( User user){
        System.out.println("user = " + user);
        return ResultData.ok();
    }
}

写入(上传)前端
1.

<form action="/upload.do" method="post" enctype="multipart/form-data">
    文件上传:<input type="file" name="source"><br/>
    <input type="submit" value="上传">
</form>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="/js/jquery-2.1.0.js"></script>
</head>
<body>
<form id="formData">
  <input type="file" name="source">
  <input type="button" onclick="ajaxupload()" value="上传">
</form>
<img width="300px" id="img" src="" alt="图片"/>
</body>
<script>
  function ajaxupload(){
      // 获得表单对象
      var formData = new FormData($("#formData")[0]);
      // 使用ajax文件上传
    $.ajax({
        url:"/upload.do",
        type:"post",
        data:formData,
        async:false,
        cache:false,
        contentType:false,
        processData:false,
      success:function (ret) {
        if (ret.code == 0) {
          console.log(ret.data)
          $("#img").attr("src",ret.data);
        }else{
          alert("上传失败1");
        }
      },
      error:function () {
        alert("上传失败2");
      }
    })
  }
</script>
</html>

写入(上传)后端

@Controller
public class IOFilrController {

    @RequestMapping("/upload")
    @ResponseBody
    public ResultData file(MultipartFile source , HttpServletRequest request)throws Exception{
        String originalFilename = source.getOriginalFilename();
        System.out.println("originalFilename = " + originalFilename);
        //随机产生图片名
        String prefix = UUID.randomUUID().toString();
        System.out.println("prefix = " + prefix);
//        获取文件后缀
        String suffix = FilenameUtils.getExtension(originalFilename);
        System.out.println("suffix = " + suffix);
//        组合成新文件名
       String filename= prefix+"."+suffix;
        System.out.println("filename = " + filename);
//        获取服务器路径
        String realPath = request.getServletContext().getRealPath("/upload_file");
        System.out.println("realPath = " + realPath);
//        创建文件夹
        File parentFile = new File(realPath);
        if(!parentFile.exists()){
            parentFile.mkdir();
        }
//开始上传
        source.transferTo(new File(parentFile,filename));
        System.out.println("parentFile = " + parentFile);
        System.out.println("filename = " + filename);
        return ResultData.ok("/upload_file/"+filename);
    }

下载前端

<div>
    <div>
        <!-- 图片路径是服务器路径 -->
        <img width="300px" src="/upload_file/3f59e343-1b13-4fd1-947e-aa20f3719f49.jpg">
        <button>
            <!-- 下载时,请求中携带文件名即可 -->
            <a href="/download.do?filename=3f59e343-1b13-4fd1-947e-aa20f3719f49.jpg">下载</a>
        </button>
    </div>
</div>

下载后端

 /**
     * 下载图片
     * 下载是需要响应一个对话框,选择文件下载到什么地方
     * 不需要跳转页面,或者返回JSON
     */
    @RequestMapping("/download")
    public void download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String realPath = request.getServletContext( ).getRealPath("/upload_file");
        String filepath = realPath+"/"+filename;

        //设置响应头 告知浏览器,要以附件的形式保存内容
        //浏览器显示的下载文件名
        response.addHeader("content-disposition","attachment;filename="+filename);
        response.setContentType("multipart/form-data");
        //读取目标文件,写出给客户端
        IOUtils.copy(new FileInputStream(filepath),response.getOutputStream());
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

想要入门的程序猿

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

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值