当前位置: 移动技术网 > IT编程>开发语言>Java > springmvc 文件上传

springmvc 文件上传

2018年07月17日  | 移动技术网IT编程  | 我要评论

这里记录下,方便以后复制粘贴。

 maven配置

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

maven将自动引入   commons-fileupload-1.3.3.jar 和 commons-io-2.2.jar

 springmvc配置

<!-- 文件上传表单的视图解析器 ,名字不要变-->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
            <property name="defaultEncoding" value="utf-8"></property>   
            <property name="maxUploadSize" value="104857600"></property>
            <property name="maxInMemorySize" value="40960"></property>  
    </bean>

页面表单

<form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/data/importdata">
            <input type="file" name="mobiles"/>
            <button type="submit">导入</button>
</form>

controller层处理,保存文件到本地

public String importData(MultipartFile mobiles) throws IOException {
        //判断是否有上传文件
        if (mobiles.getSize()>0) {
            //存储到本地的路径
            String path = "/app/updata/";
            File filepath = new File(path);
            //目录不存在则创建目录
            if (!filepath.exists()) {
                filepath.mkdirs();
            }
            //路径+随机生成一个不容易重复的文件名+原文件名
            String pathandfile = path+IdrandomUtil.getStringRandom(10)+mobiles.getOriginalFilename();
            //将上传文件写入本地
            mobiles.transferTo(new File(pathandfile));
        }else{
            return "请选择上传文件";
        }
        return "成功";
}

 

嗯,我觉得文章就得这么写,简单明了。 复制粘贴就能用。

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网