springmvc实现多图片上传:

主要是项目要做的是一个发表分享的功能,就有点像微信发朋友圈那样,一个内容文字和图片显示。

思路:用form表单提交,在form表单选择多张图片,有文字说明,后台springmvc接受数据。接受数据有文字,有多张图片,有是谁发表分享的用户id。那就用一个类把这些数据封装起来;之后把这些数据存到数据库里。

工具:IDEA

数据库:mysql

页面:jsp

前端页面:

<div class="col-sm-6 col-xs-12 my_edit" >
    <div class="row" id="edit_form" >
        <span class="pull-left" style="margin:15px;">编写新鲜事</span>
        <span class="tips pull-right" style="margin:15px;"></span>
        <form role="form" id="fileform" action="<%=request.getContextPath()%>/upload/uploadfiles" method="post" enctype="multipart/form-data" style="margin-top: 50px;">
            <div class="form-group">
                <div class="col-sm-12"  >

                        <textarea id="content"  name="content" rows="2" cols="20" style="width: 343px;height: 95px"></textarea>
                </div>
                <input type="hidden" name="userid" value="user19@qq.com">
                <br>
                <div id="spu_img">
                    <div id="spu_img_div_0" style="border:1px solid #333;width:80px;height:80px;float:left;">
                        <img id = "img_0" style="cursor:pointer" src="<%=request.getContextPath()%>/public/content/publishContent/img/pic.png" width="80px" height="80px" οnclick="spu_add_img_click(0)"/>
                        <input id="file_0"  type="file" name="files" style="display:none;" onChange="spu_add_img_change(0)" /><br>
                    </div>
                </div>
                <div class="col-sm-12" style="margin-top: 12px;">
                    <button class="btn btn-default btn-search" name="search" type="submit" οnclick="search()">发布</button>
                </div>
            </div>
        </form>
    </div>

使用js通过点击图片来显示我们选择的图片

<script type="text/javascript">

    function spu_add_img_click(index){if (index<3){// 调用按钮对应的file对象的点击事件
            $("#file_"+index).click();
        }else{alert("文件只能上传3张");
        }}function spu_add_img_change(index){// 获得图片缓存
        var blob = $("#file_"+index)[0].files[0];

        // 转化成url
        var url = window.URL.createObjectURL(blob);

        // 赋值给src
        $("#img_"+index).attr("src",url);

        // 判断用户当前点击的图片是不是组后一个按钮图片
        var length = $("#spu_img :file").length;
        if((length-1)==index){spu_add_img_add(index);
        }}function spu_add_img_add(index){var a = '<div id="spu_img_div_'+(index+1)+'" style="margin-left:10px;border:1px solid #333;width:80px;height:80px;float:left;">';
        var b = '<img id = "img_'+(index+1)+'" style="cursor:pointer" src="<%=request.getContextPath()%>/public/content/publishContent/img/pic.png" width="80px" height="80px" οnclick="spu_add_img_click('+(index+1)+')"/>';
        var c = '<input id="file_'+(index+1)+'"  type="file" name="files" style="display:none;" onChange="spu_add_img_change('+(index+1)+')" /><br>';
        var d = '</div>';
        $("#spu_img").append(a+b+c+d);

    }</script>

点击发布把数据发到后台,springmvc接受数据。把userid,content,files封装成一个ContentByImg类,让springmvc通过自动注入方式获取从前端页面传过来的值

public class ContentByImg implements Serializable {private String userid;
    private String content;
    private MultipartFile[] files;

    public ContentByImg() {}public String getUserid() {return userid;
    }public void setUserid(String userid) {this.userid = userid;
    }public String getContent() {return content;
    }public void setContent(String content) {this.content = content;
    }public MultipartFile[] getFiles() {return files;
    }public void setFiles(MultipartFile[] files) {this.files = files;
    }@Override
    public String toString() {return "ContentByImg{" +"userid='" + userid + '\'' +", content='" + content + '\'' +", files.sieze()=" + files.length +'}';
    }
}

springmvc后台处理,对应多张图片又有一个文件处理类来处理,处理完返回图片的名字集合,因为数据库的content表设计的是放3张图片,所以要用一个数组把多张图片的名字插入数据表中。

/**
 * 文件上传处理
 * Created by ASUS on 2018/5/10
 *
 * @Authod Grey Wolf
 */
import java.io.File;
import java.util.List;

import net.stxy.one.model.Content;
import net.stxy.one.model.ContentByImg;
import net.stxy.one.model.Page;
import net.stxy.one.service.ContentService;
import net.stxy.one.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/upload")
public class UploadController {@Autowired
    private FileUtils fileUtils;

    @Autowired
    private ContentService contentService;

    @RequestMapping("uploadfiles")public String uploadfiles(ContentByImg contentByImg,Model model) {System.out.println("---content:0"+contentByImg.toString());
        // 上传图片,返回图片名称集合
        List<String> list_image = fileUtils.getImgPath(contentByImg.getFiles());
        String []pic=new String[3];
        int i=0;
        for (String s:list_image){System.out.println("filename:"+s);
            pic[i++]=s;
        }Content content1=new Content();
        content1.setPic1(pic[0]);
        content1.setPic2(pic[1]);
        content1.setPic3(pic[2]);
        content1.setContent(contentByImg.getContent());
        content1.setUserid(contentByImg.getUserid());//把数据插入到数据库content表中contentService.insertContent(content1);

        Page page=new Page(3,0);//查询数据库content表,获取结果集合,在页面显示刚才发布的信息,图片List<Content>listCotent=contentService.selectPageList(page);
        model.addAttribute("listContent",listCotent);
        return "index";
    }}
/**
 * Created by IntelliJ IDEA
 * User: Litongxue
 * Time: 2018/5/2
 * Description: TODO 文件操作工具类
 */
@Component
public class FileUtils {//文件储存路径
    private final static String UPLOADURL="C:\\Users\\ASUS\\Pictures\\SharedImageServer\\contentpic\\";

    public String createFileName(String originalFilename) {String hzm = originalFilename.split("\\.")[1];
        return UUID.randomUUID().toString().replace("-", "") + "." + hzm;
    }public  String getFileName(String originalFilename){String fileName=String.valueOf(System.currentTimeMillis()) + "." + originalFilename;
        return fileName;
    }public List getImgPath(MultipartFile[] files) {List<String> list = new ArrayList<>();
//        String uploadUrl = "C:\\Users\\ASUS\\Pictures\\SharedImageServer\\contentpic\\";
        for (MultipartFile file : files) {if("".equals(file.getOriginalFilename())){continue;
            }//获取上传图片的文件名,变为时间+图片名
            String fileName = getFileName(file.getOriginalFilename());
            System.out.println("filename:" + fileName);
            String filePath = UPLOADURL + fileName;
            //创建文件对象
            File tagetFile = new File(UPLOADURL + fileName);
            list.add(fileName);
            //文件名不存在 则新建文件,并将文件复制到新建文件中
            if (!tagetFile.exists()) {try {tagetFile.createNewFile();
                } catch (IOException e) {e.printStackTrace();
                }try {//保存图片
                    file.transferTo(tagetFile);
                } catch (IllegalStateException e) {e.printStackTrace();
                } catch (IOException e) {e.printStackTrace();
                }}}for (String s : list) {System.out.println("s;::" + s);
        }return list;
    }}

why:为什么是把图片名字插进去,而不是把图片的全路径插进去呢?

因为我选择的不是把多张图片直接传到我的项目文件夹下,而是选择存到电脑其他盘的文件下,所以选择使用nginx作为图片服务器,只要打开nginx服务器,那么jsp页面的图片路径src=nginx设置的路径+数据库存的图片名字就可以显示了。

不会搭建图片服务器可以看看:Windows实现nginx作为图片服务器

我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。

springmvc实现多图片上传相关推荐

  1. 用SpringMVC框架实现图片上传与下载

    1.新建一个Maven webapp项目,引入需要用的夹包,pom.xml文件的依赖包如下: <dependencies><!-- 用于生成图片的缩略图 --><depe ...

  2. Ueditor1.4.3.3+springMvc+maven 实现图片上传

    前记:由于项目中需要有一个新增数据并且要能支持表格图片上传的功能.使用了ueditor控件.为实现这个功能,从一开始什么都看不懂,到一直连着弄了5天,总算是有了眉目.在此记录一下以便能帮到可以和我一样 ...

  3. springMVC+jquery实现图片上传

    需要的jar包,添加maven依赖 <dependency><groupId>commons-fileupload</groupId><artifactId& ...

  4. SpringMVC入门(二)—— 参数的传递、Controller方法返回值、json数据交互、异常处理、图片上传、拦截器

    SpringMVC入门(二)-- 参数的传递.Controller方法返回值.json数据交互.异常处理.图片上传.拦截器 参考文章: (1)SpringMVC入门(二)-- 参数的传递.Contro ...

  5. java多图片上传json_[Java教程]SpringMVC框架五:图片上传与JSON交互

    [Java教程]SpringMVC框架五:图片上传与JSON交互 0 2018-08-07 22:00:42 在正式图片上传之前,先处理一个细节问题: 每一次发布项目,Tomcat都会重新解压war包 ...

  6. SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传

    SpringMVC:学习笔记(10)--整合Ckeditor且实现图片上传 配置CKEDITOR 精简文件 解压之后可以看到ckeditor/lang下面有很多语言的js,如果不需要那么多种语言的,可 ...

  7. element显示服务器的图片,Vue+ElementUI+SpringMVC实现图片上传和回显

    Vue+ElementUI+SpringMVC实现图片上传和table回显 而我们也常遇到表单中包含图片上传的需求,并且需要在table中显示图片,所以这里我就讲一下结合后端的SpringMVC框架如 ...

  8. Vue+ElementUI+SpringMVC实现图片上传和回显

    Vue+ElementUI+SpringMVC实现图片上传和table回显 在之前我们已经讲过了 Vue+ElementUI+SpringMVC实现分页 . 而我们也常遇到表单中包含图片上传的需求,并 ...

  9. java图片上传并解析,详解SpringMVC实现图片上传以及该注意的小细节

    本篇文章主要介绍了详解SpringMVC实现图片上传以及该注意的小细节,具有一定的参考价值,感兴趣的小伙伴们可以参考一下. 先附上图片上传的代码 jsp代码如下: ![](${path}/mall/i ...

  10. Spring+SpringMVC+MyBatis明日方舟版人员信息管理系统前端页面代码前后端交互+SSM框架 管理员登录 游客登录 普通用户登录 人员的增删改查 信息更新 图片上传 分页查询)

    Spring+SpringMVC+MyBatis明日方舟版人员信息管理系统前端页面代码(前后端交互+SSM框架 管理员登录 游客登录 普通用户登录 人员的增删改查 信息更新 图片上传 分页查询 修改密 ...

最新文章

  1. java怎么通过ip地址查具体地址_制作通过IP 查询地址的java版程序
  2. 常用的数据结构_三分钟了解区块链常用数据结构「默克尔树」
  3. DriverMessageBean配置详解
  4. 查看Oracle表中的指定记录在数据文件中的位置
  5. assert.notDeepEqual()
  6. AutoCAD2008换硬盘后重新激活
  7. c3p0 mysql 连接池配置文件_使用XML配置c3p0数据库连接池
  8. 剑指MBA?Acer发布全高清触控Win8平板Aspire S7
  9. C与指针——指针(一)
  10. win10更改C盘下的用户文件夹名
  11. 计算机桌面不同步,怎样使电脑桌面文件在不同桌面位置上显示
  12. vue引入组件路径报错“Already included file name ”
  13. u盘里删除的文件可以恢复吗?分享解决方法
  14. 湖人行--(kobe bryant)
  15. Dart语言(一)--基础语法
  16. 英语-非谓语动词作定语
  17. 完全限定域名(fully qualified domain name,FQDN,笔记)
  18. Java将Unicode转换成中文
  19. W32TM注册time.windows.com作为权威时间同步源
  20. 解读:通过挖掘股票内在特征预测股票趋势

热门文章

  1. matlab axis函数_又是被Matlab整疯的一天!来学点简单操作!
  2. MATLAB中log算子处理图像
  3. Matlab更改计算机用户名
  4. 联想笔记本S10电池拆解
  5. GeoLite2-City.mmdb 下载方法
  6. 遗传算法原理及算法步骤(学习篇·上)
  7. matlab灵敏度分析绘图——道路最大通行能力
  8. 信息安全和网络空间安全
  9. 计算机毕业设计-SSM企业OA管理系统-JavaWeb企业OA管理系统
  10. 弹性均质圆环法计算过程_均质圆环胎刚体的转动惯量