springboot 单个input多图片上传

最近有用到多图片上传的功能,但是不能有多少个图片就写多少个标签,于是在网上找了一个js展现图片的模板,自己改造之后实现了单个input上传多个图片的功能。

1.项目是基于springboot

快速搭建springboot: http://start.spring.io/
项目名是studySpringBoot,如下图,如不想搭建,可以直接用我后面的百度云源代码
springboot 单个input多图片上传_第1张图片

2.前台代码如下:

uploadImg.html
  1. <html>
  2. <head>
  3. <meta charset="utf-8">
  4. <title>一个input实现多图片上传 title>
  5. <script src="js/jquery.min.js"> script>
  6. <script src="js/uploadImg.js"> script>
  7. <style type="text/css"> style>
  8. <link rel="stylesheet" type="text/css" href="css/uploadImg.css">
  9. head>
  10. <body>
  11. <form action="" id="upBox">
  12. 小区名字: <input name="areaName">
  13. <div id="inputBox">
  14. <input type="file" name="file" title="请选择图片" id="file" multiple="multiple" accept="image/png,image/jpg,image/gif,image/JPEG"/>选择图片
  15. div>
  16. <div id="imgBox">
  17. div>
  18. <button id="btn">上传 button>
  19. form>
  20. body>
  21. <script type="text/javascript">
  22. imgUpload({
  23. inputId: 'file', //input框id
  24. imgBox: 'imgBox', //图片容器id
  25. buttonId: 'btn', //提交按钮id
  26. upUrl: '/testController/uploadImg', //提交地址
  27. data: 'file', //参数名
  28. num: "10" //最多上传图片个数
  29. })
  30. script>
  31. html>
uploadImg.js
  1. var imgSrc = []; //存放图片路径
  2. var imgFile = []; //存放文件流
  3. var imgName = []; //存放图片名字
  4. //选择图片的操作
  5. function imgUpload(obj) {
  6. var oInput = '#' + obj.inputId;
  7. var imgBox = '#' + obj.imgBox;
  8. var btn = '#' + obj.buttonId;
  9. //用on是因为它可以动态的绑定事件
  10. $(oInput).on("change", function() {
  11. //获取type=file的input
  12. var fileImg = $(oInput)[0];
  13. //得到所有的图片列表
  14. var fileList = fileImg.files;
  15. for(var i = 0; i < fileList.length; i++) {
  16. //得到每个图片的路径
  17. var imgSrcI = getObjectURL(fileList[i]);
  18. //向文件名的数组末尾添加此文件名
  19. imgName.push(fileList[i].name);
  20. //向路径的数组末尾添加路径
  21. imgSrc.push(imgSrcI);
  22. //在文件流数组的末尾添加文件
  23. imgFile.push(fileList[i]);
  24. }
  25. //将图片展示出去
  26. addNewContent(imgBox);
  27. })
  28. $(btn).on('click', function() {
  29. if(!limitNum(obj.num)){
  30. alert("最多只能上传"+obj.num+"张照片!");
  31. return false;
  32. }
  33. //用FormData对象上传
  34. var fd = new FormData($('#upBox')[0]);
  35. //由于fd对象中已经包含<input type='file'>的input标签,如果不删除,就会造成重复上传
  36. fd.delete("file");
  37. //将文件流循环添加到FormData对象中
  38. for(var i=0;i <imgFile.length;i++){
  39. fd.append(obj.data,imgFile[i]);
  40. }
  41. //上传所有的图片
  42. submitPicture(obj.upUrl, fd);
  43. })
  44. }
  45. //图片展示
  46. function addNewContent(obj) {
  47. $(imgBox).html("");
  48. for(var a = 0; a < imgSrc.length; a++) {
  49. var oldBox = $(obj).html();
  50. $(obj).html(oldBox + '<div class="imgContainer"> <img title=' + imgName[a] + ' alt=' + imgName[a] + ' src=' + imgSrc[a] + ' onclick="imgDisplay(this)"> <p onclick="removeImg(this,' + a + ')" class="imgDelete">删除 p> div>');
  51. }
  52. }
  53. //删除
  54. function removeImg(obj, index) {
  55. //向数组中删除元素
  56. imgSrc.splice(index, 1);
  57. imgFile.splice(index, 1);
  58. imgName.splice(index, 1);
  59. var boxId = "#" + $(obj).parent('.imgContainer').parent().attr("id");
  60. addNewContent(boxId);
  61. }
  62. //限制图片个数
  63. function limitNum(num){
  64. if(!num){
  65. return true;
  66. }else if(imgFile.length>num){
  67. return false;
  68. }else{
  69. return true;
  70. }
  71. }
  72. //上传(将文件流数组传到后台)
  73. function submitPicture(url,data) {
  74. for (var p of data) {
  75. console.log(p);
  76. }
  77. if(url&&data){
  78. $.ajax({
  79. type: "post",
  80. url: url,
  81. async: true,
  82. data: data,
  83. //下面这两个要写成false,要不然上传不了。
  84. processData: false,
  85. contentType: false,
  86. success: function(dat) {
  87. console.log(dat);
  88. }
  89. });
  90. }else{
  91. alert('数据格式不正确!');
  92. }
  93. }
  94. //当鼠标移到图片上时,显示x删除
  95. function imgDisplay(obj) {
  96. var src = $(obj).attr("src");
  97. var imgHtml = ' <div style="width: 100%;height: 100vh;overflow: auto;background: rgba(0,0,0,0.5);text-align: center;position: fixed;top: 0;left: 0;z-index: 1000;"> <img src=' + src + ' style="margin-top: 100px;width: 70%;margin-bottom: 100px;"/> <p style="font-size: 50px;position: fixed;top: 30px;right: 30px;color: white;cursor: pointer;" onclick="closePicture(this)">× p> div>'
  98. $('body').append(imgHtml);
  99. }
  100. //关闭
  101. function closePicture(obj) {
  102. $(obj).parent("div").remove();
  103. }
  104. //图片预览路径
  105. function getObjectURL(file) {
  106. var url = null;
  107. if(window.createObjectURL != undefined) { // basic
  108. url = window.createObjectURL(file);
  109. } else if(window.URL != undefined) { // mozilla(firefox)
  110. url = window.URL.createObjectURL(file);
  111. } else if(window.webkitURL != undefined) { // webkit or chrome
  112. url = window.webkitURL.createObjectURL(file);
  113. }
  114. return url;
  115. }

3.在src/main/java下建立一个包controller,包下面有两个类,一个是用来启动主程序,一个用来上传图片。由于功能简单,我这里就没写service,用到项目里面的时候要尽可能把业务处理写到service中去。

SampleController
  1. package controller;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  4. import org.springframework.context.annotation.ComponentScan;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. @Controller
  9. @EnableAutoConfiguration
  10. @ComponentScan("controller")
  11. public class SampleController {
  12. @RequestMapping("/test")
  13. @ResponseBody
  14. String home() {
  15. return "Hello World!";
  16. }
  17. public static void main(String[] args) throws Exception {
  18. SpringApplication.run(SampleController.class, args);
  19. }
  20. }

UploadImageController
  1. package controller;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.ResponseBody;
  7. import org.springframework.web.multipart.MultipartFile;
  8. @Controller
  9. @RequestMapping( "/testController")
  10. public class UploadImage {
  11. @RequestMapping( "/uploadImg")
  12. @ResponseBody
  13. public void uploadImg(MultipartFile file[], String areaName) throws Exception {
  14. System.out.println( "得到的areaName:"+areaName);
  15. // 设置上传的路径是D盘下的picture
  16. String imgPath = "D:/picture/";
  17. for (MultipartFile f : file) {
  18. // 图片的名字用毫秒数+图片原来的名字拼接
  19. System.out.println(f.getSize());
  20. System.out.println(f.getBytes());
  21. String imgName = System.currentTimeMillis() + f.getOriginalFilename();
  22. //上传文件
  23. uploadFileUtil(f.getBytes(), imgPath, imgName);
  24. }
  25. }
  26. /**
  27. * 上传文件的方法
  28. * @param file:文件的字节
  29. * @param imgPath:文件的路径
  30. * @param imgName:文件的名字
  31. * @throws Exception
  32. */
  33. public void uploadFileUtil(byte[] file, String imgPath, String imgName) throws Exception {
  34. File targetFile = new File(imgPath);
  35. if (!targetFile.exists()) {
  36. targetFile.mkdirs();
  37. }
  38. FileOutputStream out = new FileOutputStream(imgPath + imgName);
  39. out.write(file);
  40. out.flush();
  41. out.close();
  42. }
  43. }
前台效果:
springboot 单个input多图片上传_第2张图片


点击上传即可把图片上传到D盘下的picture文件夹下。

你可能感兴趣的:(转载)