springboot+vue 交互上传多张图片案例

  vue前端使用element框架

使用了var formData = new FormData();处理数据传输到后端处理

效果图附上

页面代码

<el-dialog :title="title" :visible.sync="dialogTableVisible">
      <el-form :model="user" status-icon ref="user" label-width="100px" enctype="multipart/form-data">
        <el-form-item label="商家英文名" style="width:48%;display: inline-block">
          <el-input v-model="user.nameEn" placeholder="商家英文名"></el-input>
        </el-form-item>
        <el-form-item label="商家名" style="width:48%;display: inline-block">
          <el-input v-model="user.name" placeholder="商家名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="pass" v-if="insertpassword" style="width:48%;display: inline-block">
          <el-input type="password" placeholder="密码" v-model="user.password" show-password></el-input>
        </el-form-item>
        <!-- <el-form-item label="密码" prop="pass" v-if="ifpassword">
          <el-input type="Password" placeholder="密码" v-model="user.oldPassword" show-password></el-input>
        </el-form-item> -->

        <el-form-item label="郵箱" style="width:48%;display: inline-block">
          <el-input v-model="user.email" placeholder="郵箱"></el-input>
        </el-form-item>
        <el-form-item label="地址" style="width:48%;display: inline-block">
          <el-input v-model="user.address" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="聯係方式" style="width:48%;display: inline-block">
          <el-input v-model="user.phone" placeholder="聯係方式"></el-input>
        </el-form-item>

                <el-form-item label="上傳商家圖片" style="width: 100%" label-width=200px;>
                  <el-upload
                    :action="IMG.imgAciton"
                    multiple
                    ref="uploadbusiness"
                    :limit="1"
                    :data="user"
                    :on-change="AddfileListtablebussiness"
                    list-type="picture"
                    class="upload-demo"
                    :before-remove="deleteImgtablebussiness"
                    :on-success="handleSuccess"
                    accept=".jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
                    :before-upload="phototable"
                    :auto-upload="false"
                    :on-exceed="outhanderror"

                  >
                    <el-button size="small" type="primary">UPLOAD</el-button>
                    <div slot="tip" class="el-upload__tip">
                      SUPPORT JEP/PNG FILEAPPEND
                      <!-- ,Do not ex/ceed 500kb -->
                    </div>
                  </el-upload>
                </el-form-item>

        <el-form-item label="上傳執照圖片" style="width: 100%" label-width=200px;>
          <el-upload
            :action="IMG.imgAciton"
            multiple
            ref="upload"
            :limit="5"
            :data="user"
            :on-change="AddfileListtable"
            list-type="picture"
            class="upload-demo"
            :before-remove="deleteImgtable"
            :on-success="handleSuccess"
            accept=".jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
            :before-upload="phototable"
            :auto-upload="false"
            :on-exceed="outhanderror"

          >
            <el-button size="small" type="primary">UPLOAD</el-button>
            <div slot="tip" class="el-upload__tip">
              SUPPORT JEP/PNG FILEAPPEND
              <!-- ,Do not ex/ceed 500kb -->
            </div>
          </el-upload>
        </el-form-item>
                <el-form-item label="上傳環境圖片" style="width: 100%" label-width=200px;>
                  <el-upload
                    :action="IMG.imgAciton"
                    multiple
                    ref="uploadsurroundings"
                    :limit="5"
                    :data="user"
                    :on-change="AddfileListtablesurroundings"
                    list-type="picture"
                    class="upload-demo"
                    :before-remove="deleteImgtablesurroundings"
                    :on-success="handleSuccess"
                    accept=".jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
                    :before-upload="phototable"
                    :auto-upload="false"
                    :on-exceed="outhanderror"

                  >
                    <el-button size="small" type="primary">UPLOAD</el-button>
                    <div slot="tip" class="el-upload__tip">
                      SUPPORT JEP/PNG FILEAPPEND
                      <!-- ,Do not ex/ceed 500kb -->
                    </div>
                  </el-upload>
                </el-form-item>

        <el-form-item style="text-align: center">
          <el-button type="primary" @click="add" icon="el-icon-plus" v-if="instalType">新增</el-button>
          <el-button type="warning" @click="add" v-if="updatepp" icon="el-icon-edit">修改</el-button>
          <el-button type="primary" @click="selectList" icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

js代码

<script>
  import { selectSystemAdUserList, addUser, deleteData } from '@/api/service/businessManagement'

  export default {

    data() {
      return {
        user: {
          id: '',
          nameEn: '',
          name: '',
          password: 0,
          oldPassword: '',
          newPassword: '',
          email: '',
          phone: '',
          address: '',
          filetable: [],
          filebussiness:[],
          filesurroundings:[],
          isDelete:"1"

        },
       
        dialogTableVisible: false,

        IMG: {
          dialogVisible: false,
          dialogImageUrl: '',
          imgShow: true,
          ifUpload: false,
          imgAciton: process.env.BASE_API + '/system/adUser/addSystemAdUserList',
          IMGPATH: '',
          fileList: [
            {
              name: 'food.jpeg',
              url:
                'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
            },
            {
              name: 'food2.jpeg',
              url:
                'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
            }
          ],
          file: [],
          filebussiness:[],
          filesurroundings: [],
          fileViolists: [],
          Fileappend: '',
          imgHeaders: {
            'X-System': getToken()
          }
        }

      }
    },
    computed: {},
    watch: {},
    created() {
    },
    mounted() {
      this.selet()
    },
    methods: {
      
      //新增模态框
      showInstallForm() {
        this.title = '新增'
        if (this.userData.roleId == 1 || this.userData.roleId == 2) {
          this.ifpassword = false
          this.selectList()
          this.instalType = true
          this.updatepp = false
          this.dialogTableVisible = true
          this.insertpassword = true
          this.iftype = true

        } else {
          this.$message.success('不是管理员,不能操作')
        }
      },
      //改变总页数
      rowsChange(val) {
        this.selectFrom.limit = val
        this.selet()
      },
      //改变总页数
      //分页
      handleCurrentChange(val) {
        this.selectFrom.page = val
        this.selet()
      },
      //行点击
      rowClick(row) {
        // this.tableDataEdit(row)
      },
      //新增
      add() {
        // if(this.user.phone==null || this.user.phoneArea==null){
        //   this.$message.error("手機號不能爲空")
        //   return;
        // }
        var formData = new FormData();
        formData.append("user", JSON.stringify(this.user)); //通过append向form对象添加数据
        for (var j = 0; j < this.IMG.file.length; j++) {
          formData.append("LicenseLogo", this.IMG.file[j].raw); //通过append向form对象添加数据

          console.log(this.IMG.file[j].raw)

        }
        for (var j = 0; j < this.IMG.filebussiness.length; j++) {

          formData.append("businessLogo",this.IMG.filebussiness[j].raw); //通过append向form对象添加数据
          console.log(this.IMG.file[j].raw)

        }
        for (var j = 0; j < this.IMG.filesurroundings.length; j++) {
          formData.append("surroundingsLogo",this.IMG.filesurroundings[j].raw); //通过append向form对象添加数据
          // this.user.filesurroundings = this.IMG.file[j].raw
          console.log(this.IMG.file[j].raw)

        }

      //有图片
      //   if (this.IMG.file.length == 1) {
      //     this.$refs.upload.submit()
      //   }
      //   if (this.IMG.filebussiness.length == 1) {
      //     this.$refs.uploadbusiness.submit()
      //   }
      //   if (this.IMG.filesurroundings.length == 1) {
      //     this.$refs.uploadsurroundings.submit()
      //   }
      //   else {//无图片
          addUser(formData)
            .then((resp) => {
              const data = resp.data
              if (data.code == 1) {
                this.dialogTableVisible = false
                this.instalType = false
                this.updatepp = false
                this.$message.success('submit successful')
                this.selet()
              } else {
                this.$message.error(data.message)
              }
            })
            .catch((error) => {
              this.$message.error(resp.message)
            })
        // }
      },
      //编辑
      tableDataEdit(row) {
        this.user.oldPassword = ''
        this.user.newPassword = ''
        this.title = '修改'

        if (row.id != this.userData.id) {
          if (this.userData.roleId == 1 || this.userData.roleId == 2) {
            this.dialogTableVisible = true
            this.instalType = false
            this.updatepp = true
            this.insertpassword = false
            this.user.id = row.id
            this.user.nameEn = row.nameEn
            this.user.name = row.name
            this.user.email = row.email
            this.user.phone = row.phone
            this.user.address = row.address
            this.ifpassword = true
            this.ifpassword = false
            this.iftype = true

          } else {
            this.$message.success('不是管理员,不能操作')
          }

        } else {
          if (this.userData.roleId == 1 || this.userData.roleId == 2) {
            this.iftype = true
          }
          this.insertpassword = true
          this.dialogTableVisible = true
          this.instalType = false
          this.updatepp = true
          this.insertpassword = false
          this.user.id = row.id
          this.user.nameEn = row.nameEn
          this.user.name = row.name
          this.user.email = row.email
          this.user.phone = row.phone
          this.user.address = row.address
          this.ifpassword = true
          this.insertpassword = true
        }
      },
      //重置
      selectList() {
        this.user.nameEn = ''
        this.user.name = ''
        this.user.password = ''
        this.user.email = ''
        this.user.phone = ''
      },
      //表格点击 删除事件
      tableDataDelType(row) {
        if (this.userData.roleId == 1 || this.userData.roleId == 2) {
          this.$confirm('此操作將刪除該类别, 是否继续?', '提示', {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning',
            beforeClose: (action, instance, done) => {
              if (action === 'confirm') {
                instance.confirmButtonLoading = true
                instance.confirmButtonText = '執行中...'
                deleteData(row.id)
                  .then((response) => {
                    const data = response.data
                    if (data.code == 1) {
                      this.$message.success('Delete successful')
                      this.selet()
                    } else {
                      this.$message.error(data.message)
                    }
                    instance.confirmButtonLoading = false
                    this.selet()
                    done()
                  })
                  .catch((error) => {
                    console.log(error)
                    this.$message.error('Network anomaly')
                    instance.confirmButtonLoading = false
                    done()
                  })
              } else {
                done()
              }
            }
          })
        } else {
          this.$message.success('不是管理员,不能操作')
        }
      },

      AddfileListtable(file, fileList) {
        this.IMG.file = fileList
      },
      deleteImgtable(file, fileList) {
        this.IMG.file = fileList
      },

      outhanderror(err, file, fileList) {
        this.$message.error('Upload up to 3 pictures')
      },
//商家圖片
      AddfileListtablebussiness(file, fileList) {
        this.IMG.filebussiness = fileList
      },
      deleteImgtablebussiness(file, fileList) {
        this.IMG.filebussiness = fileList
      },

      outhanderror(err, file, fileList) {
        this.$message.error('Upload up to 3 pictures')
      },
      //環境圖片filesurroundings
      AddfileListtablesurroundings(file, fileList) {
        this.IMG.filesurroundings = fileList
      },
      deleteImgtablesurroundings(file, fileList) {
        this.IMG.filesurroundings = fileList
      },

      outhanderror(err, file, fileList) {
        this.$message.error('Upload up to 3 pictures')
      },
      phototable(file) {},
      handleSuccess() {},



    },
    created() {

    }

  }

</script>

前端调用api

import request from '@/utils/request'
//自己封装的请求方式
export function addUser(data) {
  return request({
    //你的后台请求地址 https://api-dev/login/login
    url: '/system/adUser/addSystemAdUserList',
    method: 'post',
    data: data
  })
}

后端请求代码写法

控制器

通过HttpServletRequest 获取请求的参数

 //新增 修改 联系人
    @RequestMapping(value = "/addSystemAdUserList")
    @ResponseBody
    @ApiOperation(value = "商家添加信息,名称,电话,邮箱,logo图片,账户,密码", notes = "商家添加信息,名称,电话,邮箱,执照图片,账户,密码’", httpMethod = "POST")
    @OperationLogAnnotation(operModul = "商家管理模块-新增或者修改商家信息",operType = "新增或者修改",operDesc = "商家添加信息,名称,电话,邮箱,logo图片,账户,密码")
    public Result addSysAdUser(HttpServletRequest request) throws ValidateException {
        Result result=iAdUserService.addSysAdUser(request);
        return result;
    }

实现层写逻辑代码

package com.noah_solutions.funshare.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.noah_solutions.funshare.common.util.ImgPath;
import com.noah_solutions.funshare.common.util.Md5Utils;
import com.noah_solutions.funshare.common.util.MyImgUtil;
import com.noah_solutions.funshare.core.error.ValidateException;
import com.noah_solutions.funshare.core.request.Result;
import com.noah_solutions.funshare.core.validate.BaseValidator;
import com.noah_solutions.funshare.core.validate.Va;
import com.noah_solutions.funshare.core.validate.Validator;
import com.noah_solutions.funshare.entity.AdUser;
import com.noah_solutions.funshare.mapper.AdUserMapper;
import com.noah_solutions.funshare.pojo.po.system.AdUserPo;
import com.noah_solutions.funshare.pojo.vo.system.AdUserVo;
import com.noah_solutions.funshare.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lizhi
 * @since 2021-01-30
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {
    //图片保存地址
    @Autowired
    private ImgPath filePath;
    @Autowired
    private IAdUserService iAdUserService;

    @Override
    public Result uploadBusinessLogo(List<MultipartFile> files, String filePathUploadurl, Integer userId) {
        Result result = Result.createSuccessResult();
        MultipartFile file = null;
        //先设置一个StringBuffer路径
        StringBuffer buf = new StringBuffer();

        //查找用户是否有图片
        AdUser user = new AdUser().selectById(userId);
        if(user!=null) {
            //判断图片是否为空
            if (user.getBusinessLogo() != null && user.getBusinessLogo() != "") {
                //图片张数
                for (int i = 0; i < user.getBusinessLogo().split(",").length; i++) {
                    //删除图片
                    MyImgUtil.deleteImg(filePathUploadurl, user.getBusinessLogo().split(",")[i]);
                }
            }
        }
        //新增图片
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    //上传图片
                    String path = MyImgUtil.installImgList("businessLogo", file, filePathUploadurl);
                    //集合储存
                    //最后一条数据
                    if (files.size() == i) {
                        buf.append(path);
                    } else {
                        buf.append(path + ",");
                    }

                } catch (Exception e) {
                    result.setCode(-1);
                    result.setMessage("图片上传失败 " + i + " => " + e.getMessage());
                    return result;
                }
            } else {
                result.setCode(-1);
                result.setMessage("图片上传失败 " + i + " because the file was empty.");
                return result;
            }
        }
        //新增或者修改到数据库
        AdUser adUser = new AdUser();
        adUser.setBusinessLogo(buf.toString());
        adUser.setId(userId);
        adUser.updateById();

        result.setCode(1);
        result.setMessage("图片上传成功");
        return result;
    }

    @Override
    @Transactional
    public Result uploadSurroundingsLogo(List<MultipartFile> files, String filePathUploadurl, Integer userId) {
        Result result = Result.createSuccessResult();
        MultipartFile file = null;
        //先设置一个StringBuffer路径
        StringBuffer buf = new StringBuffer();

        //查找用户是否有图片
        AdUser user = new AdUser().selectById(userId);
        if (user != null) {
            //判断图片是否为空
            if (user.getSurroundingsLogo() != null && user.getSurroundingsLogo() != "") {
                //图片张数
                for (int i = 0; i < user.getSurroundingsLogo().split(",").length; i++) {
                    //删除图片
                    MyImgUtil.deleteImg(filePathUploadurl, user.getSurroundingsLogo().split(",")[i]);
                }
            }
        }
        //新增图片
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    //上传图片
                    String path = MyImgUtil.installImgList("surroundingsLogo", file, filePathUploadurl);
                    //集合储存
                    //最后一条数据
                    if (files.size() == i) {
                        buf.append(path);
                    } else {
                        buf.append(path + ",");
                    }

                } catch (Exception e) {
                    result.setCode(-1);
                    result.setMessage("图片上传失败 " + i + " => " + e.getMessage());
                    return result;
                }
            } else {
                result.setCode(-1);
                result.setMessage("图片上传失败 " + i + " because the file was empty.");
                return result;
            }
        }
        //新增或者修改到数据库
        AdUser adUser = new AdUser();
        adUser.setSurroundingsLogo(buf.toString());
        adUser.setId(userId);
        adUser.updateById();

        result.setCode(1);
        result.setMessage("图片上传成功");
        return result;
    }

    @Override
    public Result uploadLicenseLogo(List<MultipartFile> files, String filePathUploadurl, Integer userId) {
        Result result = Result.createSuccessResult();
        MultipartFile file = null;
        //先设置一个StringBuffer路径
        StringBuffer buf = new StringBuffer();

        //查找用户是否有图片
        AdUser user = new AdUser().selectById(userId);
        if (user != null) {
            //判断图片是否为空
            if (user.getLicenseLogo() != null && user.getLicenseLogo() != "") {
                //图片张数
                for (int i = 0; i < user.getLicenseLogo().split(",").length; i++) {
                    //删除图片
                    MyImgUtil.deleteImg(filePathUploadurl, user.getLicenseLogo().split(",")[i]);
                }
            }
        }
        //新增图片
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    //上传图片
                    String path = MyImgUtil.installImgList("LicenseLogo", file, filePathUploadurl);
                    //集合储存
                    //最后一条数据
                    if (files.size() == i) {
                        buf.append(path);
                    } else {
                        buf.append(path + ",");
                    }

                } catch (Exception e) {
                    result.setCode(-1);
                    result.setMessage("图片上传失败 " + i + " => " + e.getMessage());
                    return result;
                }
            } else {
                result.setCode(-1);
                result.setMessage("图片上传失败 " + i + " because the file was empty.");
                return result;
            }
        }
        //新增或者修改到数据库
        AdUser adUser = new AdUser();
        adUser.setLicenseLogo(buf.toString());
        adUser.setId(userId);
        adUser.updateById();

        result.setCode(1);
        result.setMessage("图片上传成功");
        return result;
    }

    @Override
    public Result addSysAdUser(HttpServletRequest request) throws ValidateException {
        List<Va> vaList = new ArrayList<>();
        Result result = Result.createSuccessResult();
//        AdUser user=new AdUser();
        MultipartHttpServletRequest params = (MultipartHttpServletRequest) request;
        List<MultipartFile> businessLogo = ((MultipartHttpServletRequest) request).getFiles("businessLogo");
        List<MultipartFile> surroundingsLogo = ((MultipartHttpServletRequest) request).getFiles("surroundingsLogo");
        List<MultipartFile> LicenseLogo = ((MultipartHttpServletRequest) request).getFiles("LicenseLogo");
        String userString = params.getParameter("user");
        AdUser user = JSON.parseObject(userString, AdUser.class);
        vaList.add(new Va(user.getName(), Validator.NOT_BLANK, "用户名"));
        BaseValidator.toValitator(vaList);//开始验证

        user.setPassword(Md5Utils.getMD5(user.getPassword()));
        //查詢是否有重複號碼
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", user.getPhone());
        AdUser adUser = new AdUser().selectOne(queryWrapper);


        System.out.println("files" + businessLogo);
        //接收前端传过来的字段
        //设置图片路径
        final String filePathUploadurl = filePath.getUploadurl();

        if (adUser != null && user.getId() != adUser.getId()) {
            result.setCode(-1);
            result.setMessage("手機號碼重複!");
            return result;
        }
        Boolean ifOk;
        if (user.getId() == null) {
            ifOk = user.insert();
            result.setMessage("新增成功");
        } else {
            ifOk = user.updateById();
            result.setMessage("修改成功");
            if (!ifOk) {
                result.setCode(-1);
                result.setMessage("修改失敗");
                return result;
            }
        }
        result = iAdUserService.uploadBusinessLogo(businessLogo, filePathUploadurl, user.getId());
        result = iAdUserService.uploadSurroundingsLogo(surroundingsLogo, filePathUploadurl, user.getId());
        result = iAdUserService.uploadLicenseLogo(LicenseLogo, filePathUploadurl, user.getId());
        result.setCode(1);
        return  result;
    }

    @Override
    public IPage<AdUserVo> selectSystemAdUserList(IPage<AdUserVo> vo, AdUserPo po) {
        return super.baseMapper.selectSystemAdUserList(vo,po);
    }
}
MyImgUtil工具类
package com.noah_solutions.funshare.common.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * author: L-z
 * date: 2019/5/5 ${time}.
 */

public class MyImgUtil {

   //单张图片上传
    public static String installImg(String path, MultipartFile file, String imgPath){

        try {

            File file1 = new File(imgPath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            String newPath = FileUtil.getCurFile();//每半月创建一个文件夹
            String fileName =System.currentTimeMillis()+".png";
            String mkdirPath =  imgPath+path+newPath;
            File targetFile = new File(mkdirPath, fileName);
            if(targetFile.exists()){
                new File(path).delete();
            }
            targetFile.mkdirs();//


                file.transferTo(targetFile);

            return path+newPath+fileName;
        }catch (Exception e){
            System.out.println("图片上传失败");
            e.printStackTrace();
            return "";
        }
    }

    public static void deleteImg(String imgs,String path){
        try{
            FileUtil.deleteFile( path+imgs);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //多张图片上传
    public static String installImgList(String path, MultipartFile file,String imgPath){

        try {
            File file1 = new File(imgPath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            String newPath = FileUtil.getCurFile();//每半月创建一个文件夹
            String fileName =System.currentTimeMillis()+".png";
            String mkdirPath =  imgPath+path+newPath;
            File targetFile = new File(mkdirPath, fileName);
            if(targetFile.exists()){
                new File(path).delete();
            }
            targetFile.mkdirs();//
            file.transferTo(targetFile);
            return path+newPath+fileName;
        }catch (Exception e){
            System.out.println("图片上传失败");
            e.printStackTrace();
            return "";
        }
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_44538423/article/details/114170008