• Spring MVC 文件上传下载


    http://mvnrepository.com/中搜索需要的包

    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.mythsky</groupId>
        <artifactId>springmvcdemo</artifactId>
        <version>1.0-SNAPSHOT</version>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.0.1.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>5.0.1.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.0.1.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.6</version>
            </dependency>
    
        </dependencies>
    
    </project>
    View Code

    registerForm.jsp

    <%--
      Created by IntelliJ IDEA.
      User: mythsky
      Date: 2017/11/21
      Time: 22:31
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>注册</title>
    </head>
    <body>
    <h3>注册页面</h3>
    <form action="register" method="post">
        <table>
            <tr>
                <td><label>登录名:</label></td>
                <td><input type="text" id="loginname" name="loginname"></td>
            </tr>
            <tr>
                <td><label>生日:</label></td>
                <td><input type="text" id="birthday" name="birthday"></td>
            </tr>
            <tr><td><input type="submit" value="登录"></td></tr>
        </table>
    </form>
    </body>
    </html>
    View Code

    FileUploadController

    package org.mythsky.springmvcdemo.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    
    
    @Controller
    public class FileUploadController {
        @RequestMapping(value = "/upload",method = RequestMethod.POST)
        public String upload(HttpServletRequest request, @RequestParam("description") String description,
                             @RequestParam("file")MultipartFile file)throws Exception{
            System.out.println(description);
            if(!file.isEmpty()){
                String path=request.getServletContext().getRealPath("/images/");
                String filename=file.getOriginalFilename();
                File filepath=new File(path,filename);
                if(!filepath.getParentFile().exists()){
                    filepath.getParentFile().mkdirs();
                }
                file.transferTo(new File(path+File.separator+filename));
                return "success";
            }else{
                return "error";
            }
        }
    }
    View Code

    虽然在maven中添加了引用,可是我本机运行的时候还是报没有找到包的错误,所以把这两个包下载下来放到lib目录中

    运行tomcat

    上传后可以找到上传文件放到了images目录下

    修改上传下载功能

    User

    package org.mythsky.springmvcdemo.model;
    
    import org.springframework.format.annotation.DateTimeFormat;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.Serializable;
    import java.util.Date;
    
    public class User implements Serializable {
        private String loginname;
        private String username;
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        private Date birthday;
        private MultipartFile image;
    
        public MultipartFile getImage() {
            return image;
        }
    
        public void setImage(MultipartFile image) {
            this.image = image;
        }
    
        public User() {
            super();
        }
    
        public String getLoginname() {
            return loginname;
        }
    
        public void setLoginname(String loginname) {
            this.loginname = loginname;
        }
    
        public Date getBirthday() {
            return birthday;
        }
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
    }
    View Code

    reguserForm.jsp

    <%--
      Created by IntelliJ IDEA.
      User: mythsky
      Date: 2017/12/5
      Time: 21:12
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>用户注册</title>
    </head>
    <body>
        <h2>用户注册</h2>
        <form action="/reguser" enctype="multipart/form-data" method="post">
            <table>
                <tr>
                    <td>用户名:</td>
                    <td><input type="text" name="username"></td>
                </tr>
                <tr>
                    <td>请上传头像:</td>
                    <td><input type="file" name="image"></td>
                </tr>
                <tr>
                    <td><input type="submit" value="注册"></td>
                </tr>
            </table>
        </form>
    </body>
    </html>
    View Code

    userInfo.jsp

    <%--
      Created by IntelliJ IDEA.
      User: mythsky
      Date: 2017/12/5
      Time: 21:15
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>文件下载</title>
    </head>
    <body>
        <h3>文件下载</h3>
        <a href="download?filename=${requestScope.user.image.originalFilename}">${requestScope.user.image.originalFilename}</a>
    </body>
    </html>
    View Code

    FileUploadController

    @RequestMapping(value = "/reguser")
        public String register(HttpServletRequest request, @ModelAttribute User user, Model model)throws Exception{
            System.out.println(user.getUsername());
            if(!user.getImage().isEmpty()){
                String path=request.getServletContext().getRealPath("/images/");
                String filename=user.getImage().getOriginalFilename();
                File filepath=new File(path,filename);
                if(!filepath.getParentFile().exists()){
                    filepath.getParentFile().mkdirs();
                }
                user.getImage().transferTo(new File(path+File.separator+filename));
                model.addAttribute("user",user);
                return "userInfo";
            }else{
                return "error";
            }
        }
        @RequestMapping(value = "/download")
        public ResponseEntity<byte[]> download(HttpServletRequest request,@RequestParam("filename")String filename,Model model)throws Exception{
            String path=request.getServletContext().getRealPath("/images/");
            File file=new File(path+File.separator+filename);
            HttpHeaders headers=new HttpHeaders();
            String downloadFileName=new String(filename.getBytes("UTF-8"),"iso-8859-1");
            headers.setContentDispositionFormData("attachment",downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
        }
    View Code

    上传页面

    下载页面

  • 相关阅读:
    ST表
    容斥原理
    扩展欧几里得算法
    C++ 快读快写模板
    单例模式的装饰器实现
    使用python+poco+夜神模拟器进行自动化测试
    使用Airtest超快速开发App爬虫
    mysql优化
    在浏览器中输入URL并回车后都发生了什么?
    第一次博客作业
  • 原文地址:https://www.cnblogs.com/uptothesky/p/7979648.html
Copyright © 2020-2023  润新知