spring实现文件上传

首先需要引入jar包

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

其次需要在配置文件中加入bean的申明

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置默认编码 -->
        <property name="defaultEncoding" value="utf-8"></property>
        <!-- 上传图片最大大小5M-->
        <property name="maxUploadSize" value="10484880"></property>
    </bean>

controller代码

 public ResultBody upFile(MultipartFile[] uploadFile) throws Exception {
        String filePath = SCMConfigUtil.getInstance().getProperty("workerSrc", "");
        if (filePath.equals("")) {
            return ResultBody.success("scm 配置错误");
        }
        // 生成文件
        filePath = filePath.substring(0, filePath.lastIndexOf('/'));
        for (MultipartFile uploadFiles : uploadFile) {
            //获取上传文件的名称
            String fileName = uploadFiles.getOriginalFilename();
            String path = filePath + File.separator + fileName;
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            uploadFiles.transferTo(file);
    }
}

前端页面代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>测试上传与下载</title>
</head>
<body>

<a href="down">down</a>
<form action="/mgr/upFile" method="post" enctype="multipart/form-data">
    头像 :<input type="file" multiple="multiple" name="uploadFile">
    <input type="submit" value="上传">

</form>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值