SpringMVC单/多文件上传

文件上传

文件上传是项目开发中最常见的功能。为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器。
一旦设置了enctype为multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据,而对于文件上传的处理则涉及在服务器端解析原始的HTTP响应。

在POM中添加文件上传的JAR包依赖
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>3.2.8.RELEASE</version>
    </dependency>
    <dependency>
		<groupId>commons-fileupload</groupId>
		<artifactId>commons-fileupload</artifactId>
		<version>1.3.1</version>
	</dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.5</version>
    </dependency>
在spring-mvc.xml中添加代码:
<!-- springMVC上传文件时,需要配置MultipartResolver处理器 -->
    <bean id="multipartResolver" 
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>
控制层代码:

FileUploadController.java

@Api(value = "文件上传操作接口", tags = {"FileUploadController"})
@RestController
@RequestMapping("/FileUpload")
public class FileUploadController {
    @Resource
    private SpringUpload springUpload;
    
    
    /**
     * @params [request]
     * @creator Conn
     * @date 2018/7/6
     * @description 单个多个文件上传接口
     */
    @ApiOperation(value = "单个多个文件上传接口", httpMethod = "POST", response = ResultInfo.class)
    @PostMapping(value = "/FileUpload", produces = {"application/json"})
    public ResultInfo FileUpload(HttpServletRequest request) {
        ResultInfo success = ResultInfo.success();
        
        try {
            Map<Integer, FastDFSFile> fastDFSFileMap = springUpload.springUpload(request);
            success.build(fastDFSFileMap);
        } catch (IOException e) {
            e.printStackTrace();
            ResultInfo.failure(e.getMessage());
        }
        return success;
    }
    
    }
业务层代码:

SpringUpload.java

@Component
public class SpringUpload {



    @Resource
    private FastDFSFileMapper fastDFSFileMapper;

    /*文件服务器的地址*/
    @Resource
    private FastDFSValueConfig fastDFSValueConfig;

    /*采用spring提供的文件上传*/
    public Map<Integer, FastDFSFile> springUpload(HttpServletRequest request) throws IllegalStateException, IOException {

        FastDFSFile fastDFSFile = null;
        Map<Integer, FastDFSFile> fastDFSFileMap = new HashMap<>();

        //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (cmr.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest msr = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = msr.getFileNames();



            while (iter.hasNext()) {
                //一次遍历所有文件
                List<MultipartFile> files = msr.getFiles(iter.next().toString());
                if (files != null) {
                    try {
                        for (MultipartFile file : files) {
                            //得到文件初始的名字
                            String fileOriginalName = file.getOriginalFilename();
                            // 取文件格式后缀名
                            String extName = fileOriginalName.substring(fileOriginalName.indexOf(".") + 1);

                            //得到文件在服务器的路径
                            String path = FastDFSUtil.uploadFile(file.getBytes(), extName);

                            //上传
                            file.transferTo(new File(fileOriginalName));


                            Double size = Double.valueOf(file.getSize());

                            fastDFSFile = new FastDFSFile();
                            Date timeStamp = Date.from(Instant.now());

                            //把值放到对象里
                            fastDFSFile.setFileOriginalName(fileOriginalName);
                            fastDFSFile.setFileOriginalSize(size);
                            fastDFSFile.setFileServerPath(path);
                            fastDFSFile.setFileUploadTime(timeStamp);

                            //添加文件信息进fastdfs_file表
                            fastDFSFileMapper.insert(fastDFSFile);

                           
                           //拼接为文件在服务器真实的地址 fastDFSFile.setFileServerPath(fastDFSValueConfig.getFastdfsAddress() + path);
                            fastDFSFileMap.put(fastDFSFile.getId(), fastDFSFile);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return fastDFSFileMap;
    }

}
用来加载文件服务器的配置文件Bean

FastDFSValueConfig.java

@Component
@PropertySource(value = "classpath:config/config_fastdfs.properties")
public class FastDFSValueConfig {

    @Value("${fastdfs.address.}")
    private String fastdfsAddress;

    public String getFastdfsAddress() {
        return fastdfsAddress;
    }

    public void setFastdfsAddress(String fastdfsAddress) {
        this.fastdfsAddress = fastdfsAddress;
    }
}
文件服务器配置文件

fastdfs-client.properties

fastdfs.tracker_servers=127.0.0.1:22122
fastdfs.connect_timeout_in_seconds=5
fastdfs.charset=UTF-8
fastdfs.http_tracker_http_port=8886
测试页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>springmvc-文件上传</title>
</head>
<body>
    <h1>使用spring MVC提供的方法上传文件</h1>
    <form name="form2" action="<c:url value='/FileUpload/FileUpload/>" method="post" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="submit" value="fileupload"/>
    </form>
</body>
</html>

综上 该接口博主测试成功,可以上传单/多个文件,并返回上传文件的信息。当然了,各位需要自己搭建文件服务器,如果不会的可以参考博主之前一个帖子。
搭建文件服务器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我的世界没光

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

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

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

打赏作者

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

抵扣说明:

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

余额充值