• 多图片上传


    pom

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>com.ylht.parent</groupId>
            <artifactId>ylht-parent</artifactId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <groupId>com.ylht.demo</groupId>
        <artifactId>ylht-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <dependencies>
            <!-- MySql -->
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
    
            <!-- Jackson Json处理工具包 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/com.jolbox/bonecp-spring -->
            <dependency>
                <groupId>com.jolbox</groupId>
                <artifactId>bonecp-spring</artifactId>
            </dependency>
    
            <!-- JSP相关 -->
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jsp-api</artifactId>
                <scope>provided</scope>
            </dependency>
    
            <!--文件上传-->
            <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
            </dependency>
    
            <!--spring-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </dependency>
    
            <!--分页插件-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
            </dependency>
            <dependency>
                <groupId>com.github.jsqlparser</groupId>
                <artifactId>jsqlparser</artifactId>
            </dependency>
    
            <!--redis.clients-->
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.6.0</version>
            </dependency>
    
            <!--MQ-->
            <dependency>
                <groupId>com.rabbitmq</groupId>
                <artifactId>amqp-client</artifactId>
                <version>3.4.1</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.amqp</groupId>
                <artifactId>spring-rabbit</artifactId>
                <version>1.4.0.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>javax.persistence</groupId>
                <artifactId>persistence-api</artifactId>
                <version>1.0</version>
            </dependency>
    
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
            </dependency>
    
            <!--通用mapper-->
            <dependency>
                <groupId>com.github.abel533</groupId>
                <artifactId>mapper</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>javax.persistence</groupId>
                        <artifactId>persistence-api</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </dependency>
    
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
            </dependency>
    
            <!-- Apache工具组件 -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-io</artifactId>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>RELEASE</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
            <dependency>
                <groupId>joda-time</groupId>
                <artifactId>joda-time</artifactId>
                <version>2.5</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <port>8082</port>
                        <path>/</path>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    spirngmvc添加

    <!-- 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>

    fileUpload.jsp

    <%@ 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>
        <script type="text/javascript" src="../../js/jquery-3.3.1.min.js"></script>
        <script type="text/javascript">
            function showImage() {
                var docObj = document.getElementById("doc");
                var imgObjPreview = document.getElementById("preview");
                if (docObj.files && docObj.files[0]) {
                    //火狐下,直接设img属性
                    imgObjPreview.style.display = 'block';
                    imgObjPreview.style.width = '300px';
                    imgObjPreview.style.height = '120px';
                    //imgObjPreview.src = docObj.files[0].getAsDataURL();
                    //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
                    imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
                } else {
                    //IE下,使用滤镜
                    docObj.select();
                    var imgSrc = document.selection.createRange().text;
                    var localImagId = document.getElementById("localImag");
                    //必须设置初始大小
                    localImagId.style.width = "250px";
                    localImagId.style.height = "200px";
                    //图片异常的捕捉,防止用户修改后缀来伪造图片
                    try {
                        localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                        localImagId.filters
                            .item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
                    } catch (e) {
                        alert("您上传的图片格式不正确,请重新选择!");
                        return false;
                    }
                    imgObjPreview.style.display = 'none';
                    document.selection.empty();
                }
                return true;
            }
    
            function showPreview(source) {
                var file = source.files[0];
                if (window.FileReader) {
                    var fr = new FileReader();
                    fr.onloadend = function (e) {
                        var pic = document.getElementById("portrait");
                        pic.style.display = 'block';
                        pic.style.width = '300px';
                        pic.style.height = '120px';
                        pic.src = e.target.result; //这个就是图片的流,可以直接展示到页面上
                    };
                    fr.readAsDataURL(file);
                }
            }
        </script>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>上传图片</title>
    </head>
    <body>
    <form action="filesUpload" method="POST" name="xiangmu" id="xiangmu"
          enctype="multipart/form-data">
        <table>
            <tr>
                <td>图片上传1:</td>
                <td><input type=file name="myfiles" id="doc"
                           onchange="showImage();">
                </td>
                <div id="localImag">
                    <img id="preview" width=-1 height=-1 style="diplay:none"/>
                </div>
            </tr>
            <tr>
                <td>图片上传2:</td>
                <!-- 为了实现张图片上传,上传框这个name要都一样 -->
                <td><input type="file" name="myfiles" id="doc1" onchange="showPreview(this)"></td>
                <div>
                    <img id="portrait" width="-1" height="-1">
                </div>
            </tr>
            <tr>
                <td><input type="submit" value="提交"/>
                </td>
            </tr>
        </table>
    </form>
    </body>
    
    </html>

    success.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8"%>
    <!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>Insert title here</title>
    </head>
    <body>
    <h2>文件上传成功!</h2>
    </body>
    </html>

    controller

    package com.ylht.manager.controller;
    
    import com.ylht.manager.service.PropertyService;
    import org.apache.commons.lang3.RandomUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.joda.time.DateTime;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    @Controller
    public class FileUpload2Controller {
    
        @Autowired
        private PropertyService propertyService;
    
        @Autowired
        private PicUploadController picUploadController;
    
    
        @RequestMapping("/filesUpload")
        //requestParam要写才知道是前台的那个数组
        public String filesUpload(@RequestParam("myfiles") MultipartFile[] files,
                                  HttpServletRequest request) {
            List<String> list = new ArrayList<String>();
            if (files != null && files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    // 保存文件
                    list = saveFile(request, file, list);
                }
            }
            //写着测试,删了就可以
            for (int i = 0; i < list.size(); i++) {
                System.out.println("集合里面的数据" + list.get(i));
            }
            return "success";//跳转的页面
        }
    
        private List<String> saveFile(HttpServletRequest request,
                                      MultipartFile file, List<String> list) {
            // 判断文件是否为空
            if (!file.isEmpty()) {
                try {
                    // 保存的文件路径(如果用的是Tomcat服务器,文件会上传到\%TOMCAT_HOME%\webapps\YourWebProject\upload\文件夹中
                    // )
                    /*String filePath = request.getSession().getServletContext()
                            .getRealPath("/")
                            + "upload/" + file.getOriginalFilename();*/
    
                    String filePath = getFilePath(file.getOriginalFilename());
    
                    list.add(file.getOriginalFilename());
                    File saveDir = new File(filePath);
                    if (!saveDir.getParentFile().exists())
                        saveDir.getParentFile().mkdirs();
    
                    // 转存文件
                    file.transferTo(saveDir);
                    return list;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return list;
        }
    
    
        private String getFilePath(String sourceFileName) {
            String baseFolder = propertyService.REPOSITORY_PATH + File.separator + "images";
            Date nowDate = new Date();
            // yyyy/MM/dd
            String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy") + File.separator + new DateTime(nowDate).toString("MM") + File.separator
                    + new DateTime(nowDate).toString("dd");
            File file = new File(fileFolder);
            if (!file.isDirectory()) {
                // 如果目录不存在,则创建目录
                file.mkdirs();
            }
            // 生成新的文件名
            String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS") + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
            return fileFolder + File.separator + fileName;
        }
    
    
    }

    主要用到的依赖jar包其实是

    <!--文件上传-->
            <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
            </dependency>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!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>Insert title here</title>
    </head>
    <body>
    <h2>文件上传成功!</h2>
    </body>
    </html>
  • 相关阅读:
    (转) 解析 char *p和 char[]
    Linux下C程序内存、内存对齐问题 (实战)
    关于子网划分的两个例子
    子网掩码与子网划分 (转载)
    A、B、C类地址及子网掩码学习笔记
    本机ip、127.0.0.1和0.0.0.0区别(转载)
    初识const
    流媒体协议
    i2c-tools的使用方法
    linux ——内存共享映射mmap和munmap
  • 原文地址:https://www.cnblogs.com/ylht/p/10243697.html
Copyright © 2020-2023  润新知