1. 程式人生 > >vue+element上傳多張圖片和圖片展示

vue+element上傳多張圖片和圖片展示

前端:

檔案上傳使用el-upload

<el-upload
	:http-request="uploadProductPic"
	accept="image/*"
	list-type="picture-card"
	:on-preview="handleContImgPreview"
	:on-remove="handleContImgRemove"
	limit="5"
	:on-exceed="exceedTips"
	:file-list="productPicPathList">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogContImgVisible" append-to-body>
<img width="100%" :src="dialogContImgUrl" />
</el-dialog>
:http-request:替代自動上傳的action

   accept:接受上傳的檔案型別

   list-type:檔案列表的型別

   on-preview:點選檔案列表中已上傳的檔案時的鉤子

   on-remove:移除以上次的檔案

   limit:限制上次的檔案個數

   :on-exceed:超出個數限制的回撥

   :file-list:檔案列表名稱

注:對於圖片的顯示有特定的json格式要求,直接返回到前端的list要封裝成要求的json格式才可以正常的展示,json格式要求如下:

[
    {
        "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"
    }
]

檔案預覽使用el-dialog

<el-dialog :visible.sync="dialogContImgVisible" append-to-body>
<img width="100%" :src="dialogContImgUrl" />
</el-dialog>

js:

 //【內容圖刪除事件】
handleContImgRemove: function (file, fileList) {
   console.log(file, fileList);
   app.productPicList.remove(file.name);
},

//內容圖數量限制3張
exceedTips: function () {
    this.$message.error('最多隻能上傳五張圖片')
},

//【內容圖片預覽事件】
handleContImgPreview: function (file) {
    this.dialogContImgUrl = file.url;
    this.dialogContImgVisible = true;
},

//上傳內容圖
uploadProductPic: function (file) {
    console.log(file)
    var fd = new FormData();
    fd.append('file', file.file);

    var content = uploadPic(fd);
    app.productPicList.push(content.attachmentId);
},

//內容圖上傳前的大小 格式的校驗
uploadProductPicBefore: function (file) {
    var fileType = file.type;
    var isJpg = false;
    if (fileType == 'image/jpeg' || fileType == 'image/png' || fileType == 'image/bmp') {
         isJpg = true;
    }
           
     if (!isJpg) {
         this.$message({
         message: '上傳的圖示只能是jpg、png、bmp格式!',
         type: 'warning'
      });
    }
   return isJpg;
},

//移除陣列中的資料
Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            return i;
        }
    }
    return -1;
}
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
}

//上傳圖片
function uploadPic(data) {
    var result = "";
    $.utils.ajax(CTX + '/cmsProductController/uploadPic', {
        type: 'post',
        contentType: false,
        data: data,
        async: false,
        processData: false,
        success: function (res) {
            if (res.success) {
                result = res.data;
                app.$message({
                    message: res.msg,
                    type: 'success'
                });
            } else {
                app.$message({
                    message: res.msg,
                    type: 'warning'
                });
                return;
            }
        }
    });
    return result;
}

Java後端:

上傳圖片:

 public VcAttachmentDo uploadPic(MultipartFile file) throws BusinessException {
        //原檔名
        String fileName = file.getOriginalFilename();
        //副檔名
        String suffixName = fileName.substring(fileName.lastIndexOf(BaseEnum.EN_POINT.getCode()) + 1);
        //檔案儲存路徑
        String filePath = prefix + File.separator + path;
        String resultPath = "";
        try {
        //上傳圖片進行路徑的返回
            resultPath = UploadUtil.uploadImage(filePath, file, suffixName);
        } catch (Exception e) {
            throw new BusinessException(CmsContentEnum.UPLOAD_FAIL.getValue(), CmsContentEnum.UPLOAD_FAIL.getCode(), e);
        }
        //新建附件表的實體類
        VcAttachmentDo vcAttachmentDo = new VcAttachmentDo();
        vcAttachmentDo.setAttachmentId(UUIDUtil.get());
        vcAttachmentDo.setFileNameSrc(fileName);
        vcAttachmentDo.setFileExt(suffixName);
        vcAttachmentDo.setFileName(resultPath.substring(resultPath.lastIndexOf(BaseEnum.BACK_SLASH.getCode())));
        vcAttachmentDo.setFilePath(path + resultPath);
        vcAttachmentDo.setStatus(BaseEnum.NUM_ONE.getCode());
        //將資料插入到附件表中
        dao.insertSelective(VcAttachmentDo.class, vcAttachmentDo);
        //將展示路徑進行拼接重新設定
        vcAttachmentDo.setFilePath(prefixPath + vcAttachmentDo.getFilePath());
        return vcAttachmentDo;
    }

上傳圖片的工具類:

 /**
     * 上傳圖片 沒做限制,符合配置檔案中大小的圖片都可上傳
     *
     * @param path
     * @param file
     * @param suffixName
     * @return
     * @throws IOException
     */
    public static String uploadImage(String path, MultipartFile file, String suffixName) throws IOException {
        //新資料夾 + 新檔名
        String newParentPath = DateUtil.dateToNoSplashString(new Date()) + File.separator;
        String filePath = newParentPath + UUIDUtil.get() + com.etom.vc.cms.utils.buenum.BaseEnum.EN_POINT.getCode() + suffixName;
        String savePath = path + File.separator + filePath;
        File saveFile = new File(savePath);
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdirs();
            saveFile.getParentFile().setReadable(true, false);
            saveFile.getParentFile().setExecutable(true, false);
            saveFile.getParentFile().setWritable(true, false);
        }
        byte[] data = file.getBytes();
        FileCopyUtils.copy(data, saveFile);
        saveFile.setReadable(true, false);
        saveFile.setWritable(true, false);
        saveFile.setExecutable(true, false);
        return (filePath).replaceAll(com.etom.vc.cms.utils.buenum.BaseEnum.FORWARD_SLASH.getCode(), com.etom.vc.cms.utils.buenum.BaseEnum.BACK_SLASH.getCode());
    }

展示圖片時:

新建一個圖片json的格式的實體類


import java.io.Serializable;

/**
 * @Author 宸
 * @Date: Created by 2019/1/4
 * @Desc:
 */
public class ImageListVo implements Serializable {

    /**
     * 圖片名稱
     */
    private String name;

    /**
     * 圖片地址
     */
    private String url;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

查詢資料:


public CmsProductVo getCurrentProduct(CmsProductVo cmsProductVo) {
List<CmsProductVo> cmsProductVoList = dao.find("cms.product.mapper.getCurrentProduct", cmsProductVo);
cmsProductVo = cmsProductVoList.get(0); 
if (StringUtils.isNotBlank(cmsProductVo.getProductPic())) {
    //用逗號將字串分開,得到字串陣列
    String[] strs = cmsProductVo.getProductPic().split(",");
    //將字串陣列轉換成集合list
    List list = Arrays.asList(strs);
    //查詢圖片集合的路徑地址
    List<VcAttachmentDo> pathList = dao.find("cms.product.mapper.find", list);
    //new一個list物件對資料進行新增
    List list1 = new ArrayList();
    for (int i = 0; i < pathList.size(); i++) {
        ImageListVo imageListVo = new ImageListVo();
        imageListVo.setUrl(prefixPath + pathList.get(i).getFilePath());
        imageListVo.setName(pathList.get(i).getAttachmentId());
        list1.add(imageListVo);
    }
    //將附件表中的主鍵插入到實體物件中,用於移除圖片和限制張數使用
    cmsProductVo.setProductPicList(list);
    //將圖片地址插入到需要的實體的類物件中
    cmsProductVo.setProductPicPathList(list1);
}
return cmsProductVo;
}
 

前端將查詢出來的資料的result物件中的productPicPathList賦值給:file-list檔案列表的顯示名稱即可展示

app.productPicPathList = result.productPicPathList;