springmvc文件上传

文件上传两种方案

  • 使用apche fileupload
  • 直接使用servlet3.0的新特性

apache方案

单文件处理方案

  • 添加依赖
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
  • 注册文件上传解析器
<!--注册文件上传解析器-->
<!--名字一定要叫multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--文件上传最大尺寸-->
    <property name="maxUploadSize" value="500000000"/>
</bean>
  • 编写页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>

<form action="/upload/m1" method="post" enctype="multipart/form-data">
`
    名称: <input type="text" name="name"><br /> <br />
    <input type="submit" value="上传">
</form>
</body>
</html>

注意必须写:enctype="multipart/form-data"

否则后台无法正确解析

  • 后台处理
package com.sz.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.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/upload")
public class UploadController {

    // 定义文件上传根路径
    private String path = "D:" + File.separator + "upload";


    @RequestMapping("/m1")
    @ResponseBody
    // 使用注解标记上传文件
    public Map<String,Integer> m1(@RequestParam("file")MultipartFile multipartFile, @RequestParam("name") String name){
        System.out.println("普通的文本域:" + name);
        // 如果不为空,再准备上传
        Map<String,Integer> map = new HashMap<>();
        int code = 4300;
        if(!multipartFile.isEmpty()) {
            BufferedOutputStream bs = null;
            try {
                byte[] bytes = multipartFile.getBytes();

                // 构建文件对象,准备上传

                File file = new File(path  );
                // 如果路径海不存在,则创建
                if(!file.exists())
                    file.mkdirs();

                // 获取文件原始名称
                String originalFilename = multipartFile.getOriginalFilename();

                // 获取文件前缀(比如hello.txt 取出hello)不含后缀
                String prefix = originalFilename.substring(0,originalFilename.lastIndexOf("."));
                // 获取文件后缀名 .txt

                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                // 上传后的文件名加上时间戳
                String newFileName =
                        prefix +
                        System.currentTimeMillis() + suffix ;

                // 构建文件对象
                File uploadFile = new File(path+ File.separator + newFileName);
                // 通过输出流写出
                bs =  new BufferedOutputStream(new FileOutputStream(uploadFile));
                bs.write(bytes);

                code = 2000;

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(bs !=null){
                    try {
                        bs.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        map.put("msg",code);
        return map;
    }



}

其实输出流处理有更简单的办法:

  • 简化
package com.sz.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.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/upload")
public class UploadController {

    // 定义文件上传根路径
    private String path = "D:" + File.separator + "upload";


    @RequestMapping("/m1")
    @ResponseBody
    // 使用注解标记上传文件
    public Map<String,Integer> m1(@RequestParam("file")MultipartFile multipartFile, @RequestParam("name") String name){
        System.out.println("普通的文本域:" + name);
        // 如果不为空,再准备上传
        Map<String,Integer> map = new HashMap<>();
        int code = 4300;
        if(!multipartFile.isEmpty()) {
            try {
                byte[] bytes = multipartFile.getBytes();

                // 构建文件对象,准备上传

                File file = new File(path  );
                // 如果路径海不存在,则创建
                if(!file.exists())
                    file.mkdirs();

                // 获取文件原始名称
                String originalFilename = multipartFile.getOriginalFilename();

                // 获取文件前缀(比如hello.txt 取出hello)不含后缀
                String prefix = originalFilename.substring(0,originalFilename.lastIndexOf("."));
                // 获取文件后缀名 .txt

                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                // 上传后的文件名加上时间戳
                String newFileName =
                        prefix +
                        System.currentTimeMillis() + suffix ;

                // 构建文件对象
                File uploadFile = new File(path+ File.separator + newFileName);
                // 通过输出流写出
                code = 2000;
                // 一行写出去
                multipartFile.transferTo(uploadFile);

            } catch (IOException e) {
                e.printStackTrace();
            }  
        }

        map.put("msg",code);
        return map;
    }



}

多文件处理方案

如果说是一组也是一样的解决方案,可以多设立几个requestparam,也可以直接一组搞定。

  • jsp
 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>

<form action="/upload/m1" method="post" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="file" name="file"><br>
    <input type="file" name="file"><br>
    名称: <input type="text" name="name"><br />
    <input type="submit" value="上传">
</form>
</body>
</html>

  • 后台
package com.sz.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.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/upload")
public class UploadController {

    // 定义文件上传根路径
    private String path = "D:" + File.separator + "upload";


    @RequestMapping("/m1")
    @ResponseBody
    // 使用注解标记上传文件
    public Map<String,Integer> m1(@RequestParam("file")MultipartFile[] multipartFiles, @RequestParam("name") String name){
        System.out.println("普通的文本域:" + name);
        // 如果不为空,再准备上传
        Map<String,Integer> map = new HashMap<>();
        int code = 4300;
        if(multipartFiles != null && multipartFiles.length > 0){
            for(MultipartFile multipartFile:multipartFiles){
                if(!multipartFile.isEmpty()) {
                    try {
                        byte[] bytes = multipartFile.getBytes();

                        // 构建文件对象,准备上传

                        File file = new File(path  );
                        // 如果路径海不存在,则创建
                        if(!file.exists())
                            file.mkdirs();

                        // 获取文件原始名称
                        String originalFilename = multipartFile.getOriginalFilename();

                        // 获取文件前缀(比如hello.txt 取出hello)不含后缀
                        String prefix = originalFilename.substring(0,originalFilename.lastIndexOf("."));
                        // 获取文件后缀名 .txt

                        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                        // 上传后的文件名加上时间戳
                        String newFileName =
                                prefix +
                                        System.currentTimeMillis() + suffix ;

                        // 构建文件对象
                        File uploadFile = new File(path+ File.separator + newFileName);
                        // 通过输出流写出
                        code = 2000;
                        multipartFile.transferTo(uploadFile);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                map.put("msg",code);
            }
        }
        return map;
    }



}

servlet3.0解决方案

将文件解析器替换为标准的解析器一样可以完成,代码可以不用发生变化

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver">

    </bean>

web.xml当中直接对DS进行参数化配置

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <multipart-config>
        <max-file-size>500000000</max-file-size>
    </multipart-config>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
posted @ 2018-09-03 06:48  沙漠皇帝  阅读(159)  评论(0编辑  收藏  举报