zoukankan      html  css  js  c++  java
  • springmvc 文件上传(粘贴即用)

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

     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 "成功";
    }

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

  • 相关阅读:
    算法竞赛入门经典习题2-3 韩信点兵
    ios入门之c语言篇——基本函数——5——素数判断
    ios入门之c语言篇——基本函数——4——数值交换函数
    144. Binary Tree Preorder Traversal
    143. Reorder List
    142. Linked List Cycle II
    139. Word Break
    138. Copy List with Random Pointer
    137. Single Number II
    135. Candy
  • 原文地址:https://www.cnblogs.com/enenen/p/9321800.html
Copyright © 2011-2022 走看看