• springMVC文件上传下载


    springmvc为文件上传提供了直接的会吃,这种支持是用即插即用的MutipartResolver实现的。springmvc使用Apache Commons FileUpload技术实现了一个MutipartResolver的实现类,CommonMultipartResolver。因此,SpringMVC的文件上传还需要依赖Apache Common FileUpload的组件

    依赖的jar包

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>1.9.13</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.47</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
            </dependency>
    

    实例代码
    uploadForm.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文件上传</title>
    </head>
    <body>
    	<h2>文件上传</h2>
    	<form action="upload" enctype="multipart/form-data" method="post">
    		<table>
    			<tr>
    				<td>文件描述:</td>
    				<td><input type="text" name="description"></td>
    			</tr>
    			<tr>
    				<td>请选择文件:</td>
    				<td><input type="file" name="file"></td>
    			</tr>
    			<tr>
    				<td><input type="submit" value="上传"></td>
    			</tr>
    		</table>
    	</form>
    </body>
    </html>
    

    负责上传文件的表单的编码类型必须是“Multipart/form-data”
    FileUploadController.java

    package com.rookie.bigdata.controller;
    
    import com.rookie.bigdata.domain.User;
    import org.apache.commons.io.FileUtils;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    
    /**
     * Created by dell on 2019/6/16.
     */
    
    @Controller
    public class FileUploadController {
    
        @RequestMapping(value = "/{formName}")
        public String loginForm(@PathVariable String formName) {
            //动态条状页面
            return formName;
        }
        // 上传文件会自动绑定到MultipartFile中
        @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("content");
                //获取上传文件名
                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";
            }
        }
        @RequestMapping(value="/register")
        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(
                        "/content/");
                // 上传文件名
                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
                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(
                    "/content/");
            File file = new File(path+File.separator+ filename);
            HttpHeaders headers = new HttpHeaders();
            // 下载显示的文件名,解决中文名称乱码问题
            String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
            // 通知浏览器以attachment(下载方式)打开图片
            headers.setContentDispositionFormData("attachment", downloadFielName);
            // application/octet-stream : 二进制流数据(最常见的文件下载)。
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 201 HttpStatus.CREATED
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                    headers, HttpStatus.CREATED);
        }
    
    
    }
    
    

    springmvc会将上传的文件绑定到MultipartFile对象中,MultipartFile提供了获取上传文件内容,文件名等方法,通过transferTo()方法将文件存储到磁盘中
    springmvc-config.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:p="http://www.springframework.org/schema/p"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd     
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.2.xsd">
            
        <context:component-scan base-package="com.rookie.bigdata.controller"/>
        
        <!-- 视图解析器  -->
         <bean id="viewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
            <!-- 前缀 -->
            <property name="prefix">
                <value>/WEB-INF/content/</value>
            </property>
            <!-- 后缀 -->
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>
        
       <bean id="multipartResolver"  
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    		<!-- 上传文件大小上限,单位为字节(10MB) -->
            <property name="maxUploadSize">  
                <value>10485760</value>  
            </property>  
            <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
            <property name="defaultEncoding">
            	<value>UTF-8</value>
            </property>
        </bean>
        
    </beans>
    

    用户点击进行文件上传就可以了

    2、使用对象接受文件
    registerForm.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>用户注册</title>
    </head>
    <body>
    	<h2>用户注册</h2>
    	<form action="register" 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>
    

    User.java

    public class User implements Serializable {
    
        private String username;
        private MultipartFile image;
    

    输入用户名并选择上传文件头像,点击注册按钮上传用户头像进入到下载页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文件下载</title>
    </head>
    <body>
    <h3>文件下载</h3>
    <a href="download?filename=${requestScope.user.image.originalFilename}">
    ${requestScope.user.image.originalFilename }
    </a>
    </body>
    </html>
    

    进入到下载页面点击下载即可

  • 相关阅读:
    【洛谷 1536】村村通
    【洛谷 1551】亲戚
    【UOJ 300】感冒病毒
    【洛谷 2299】Mzc和体委的争夺战
    【洛谷 3371】模板_单源最短路径(弱化版)
    【洛谷 2910】寻宝之路
    【洛谷 1359】租用游艇
    【UOJ 275】最短路径问题
    【UOJ 38】 股票经济人通信网络
    【UOJ 276】无向图最小环
  • 原文地址:https://www.cnblogs.com/haizhilangzi/p/11031410.html
Copyright © 2020-2023  润新知