SpringBoot+VUE[el-upload]图片上传显示

646 阅读3分钟

​主页:写程序的小王叔叔的博客欢迎****来访

支持:点赞​收藏​关注

一、效果

二、vue

页面代码:

  <!--列表-->
        <el-table border :data="productList" highlight-current-row v-loading="listLoading" style="width: 100%;"  >
              <el-table-column prop="productId" label="编号" width="150"></el-table-column>
              <el-table-column prop="original" label="图片" width="150" align="center" >
                   <template slot-scope="scope">
                    <img :src="scope.row.original" v-if="scope.row.original != null && scope.row.original.length != 0" width="40" height="40" class="head_pic"/>
                        <p v-else>未上传</p>
                  </template>
              </el-table-column>
              <el-table-column prop="productName" label="名称" width="250" show-overflow-tooltip></el-table-column>
              <el-table-column prop="productSn" label="货号" show-overflow-tooltip></el-table-column>
              <el-table-column prop="productSpec" label="种类" show-overflow-tooltip></el-table-column>
              <el-table-column prop="productSpec" label="规格" show-overflow-tooltip></el-table-column>
              <el-table-column prop="productSpec" label="品牌" show-overflow-tooltip></el-table-column>
              <el-table-column prop="marketEnable" label="是否上架" :formatter="marketEnableFormatter"></el-table-column>
              <el-table-column prop="intro" label="详情" width="100" show-overflow-tooltip></el-table-column>
              <el-table-column prop="createTime" label="创建时间" :formatter="dateFormatter"></el-table-column>
              <el-table-column label="操作">
                  <template slot-scope="scope">
                      <el-button size="small" @click="handleEdit(scope.$index, scope.row)" icon="el-icon-edit" title="修改"></el-button>
                      <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)"  title="删除"  icon="el-icon-delete"></el-button>
                </template>
          </el-table-column>
        </el-table>

<!--编辑弹窗-->
<el-dialog title="商品信息" width="40%" style="padding:10px 30px;"  v-model="editFormVisible" :visible.sync="dialogFormVisible" :close-on-click-modal="false" >
               <el-form :model="editForm" label-width="80px" ref="editForm"  >
                      <el-form-item label="Logo">
                        <el-upload   
                                    class="avatar-uploader" 
                                    :action="uploadUrl" :show-file-list="false"  
                                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" >
                          <img v-if="original" :src="original"  class="avatar" />
                          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                      </el-form-item>
                      <el-form-item label="名称">
                        <el-input v-model="editForm.productName" placeholder="请输入商品名称"></el-input>
                      </el-form-item>

                       
                      
                  <div slot="footer" class="dialog-footer">
                      <el-button @click.native="dialogFormVisible=false">取消</el-button>
                      <el-button type="primary" @click.native="editSubmit('editForm')" >提交</el-button>
                  </div>
      </el-dialog>

在js位置:
import axios from 'axios';//配置服务器请求地址链接
 data() {
    return {
      input: "",
       original:"",      
      uploadUrl:axios.defaults.baseURL+'/ImgUpload/picture',
    };
  },

 handleAvatarSuccesshandleAvatarSuccess(res, file) {
      this.original = URL.createObjectURL(file.raw);//上传图片成功后页面回显
      //上传图片自定义绝对地址
      this.editForm.original = axios.defaults.baseURL + res.success ;    
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传图片是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      let fd = new FormData();//通过form数据格式来传
      fd.append("file", file); //绑定传递参数
      var url = this.uploadUrl;
      axios.post(url, fd).then(res => {
          let data = res.data;
          if (data.code == 200) {
            this.$message({
              message: "上传成功",
              type: "success"
            });
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch(error => { });
      return isJPG ||isPNG && isLt2M;//成功上传后 返回所传图片
    },

三、springboot

1.创建上传插件要请求的链接,对应上图中的 :action="uploadUrl"

/****
 * 商品图片上传到服务器
 * @ClassName: ProductImgUpload
 * @Description: TODO(描述)
 * @author author
 * @date 2020-01-07 10:03:31
 */
@CrossOrigin
@RestController
@RequestMapping("/ImgUpload")
public class ProductImgUpload {
	
	
	/***
	 * 
	 * @Title: pictureToBASE64
	 * @Description: TODO(描述)
	 * @param request
	 * @param path
	 * @param file
	 * @return
	 * @author author
	 * @date 2020-01-07 11:25:09
	 */
	
	@PostMapping(value = "/picture", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Map<String,Object> picture(HttpServletRequest request, 
    								@RequestParam(value = "file", required = false) MultipartFile  MultiFile ) {
		Map<String,Object> map = new HashMap<String, Object>();
		try {
			//file = MultipartFileToFile.multipartFileToFile(MultiFile);
				
				map.put("success", ImgFileUtils.upload(MultiFile,request));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}

2、创建具体上传图片的工具类

public class ImgFileUtils {
	
	private static SimpleDateFormat df = new SimpleDateFormat("yyyyMM");  

	/**
     *
     * @param file 文件
     * @param filePath 文件存放路径
     * @param fileName 源文件名
     * @return
     */
	//添加AOP注解日志管理
	  @SysLogAspectValue(
			describtion = "上传图片信息",
			logType = "2",
			type="POST",
			url="/ImgUpload/picture",
			table="",
			params = "file",
			method = "POST"
	)  
    public static String upload(MultipartFile multipartFile ,  HttpServletRequest request) throws Exception {

	 	//文件夹路径  
        String folderUrl =  SysConfigModel.defaultFolderUrl +  df.format(new Date()) + "/" ;
        //文件路径
        String filePath = folderUrl +   multipartFile.getOriginalFilename();
        try {
            //将图片保存到static文件夹里
        	 //存储路径可在配置文件中指定
            File pfile = new File(folderUrl);
            if (!pfile.exists()) {
            	pfile.mkdirs();
    		}
        	multipartFile.transferTo(new File(filePath)); //创建文件  
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return filePath.subSequence(2, filePath.length()).toString();//保存图片路径时 去掉前缀固定file:D:的标识
          
    }
    
}

3、补充spring.xml中指定的配置项

/***
 * 配置文件标识
 * @ClassName: CommonPrefixModel
 * @Description: TODO(描述)
 * @author author
 * @date 2019-12-09 03:19:24
 */
@ConfigurationProperties
@PropertySource({"classpath:application.properties"})
public class SysConfigModel {

	
	 
   
	@Value(value="${spring.path.system.default.img.fold.url}")
	public static String defaultFolderUrl="D:/images/supermarket/";//指定本地文件夹存储
	@Value(value="${spring.path.system.default.img.file.url}")
	public static String defaultFileUrl="file:D:/images/supermarket/";//指定本地文件存储
	  
	
	
}

4、spring.xml文件

##-----------------------------------------------------------------------------------------
##
##修改当前文件内容时,同时要修改文件名:SysConfigModel.java 文件中的相关对应的内容
##
##-------------------------------------------------------------------------------------------------------
#==============================业务主键标号标识===================================


##上传图片的文件夹路径 -----file:D:------这个去掉直接不使用 用来上传图片用
spring.path.system.default.img.fold.url=D:/images/supermarket/


##上传图片的图片文件路径 -----file:D:------这个不能去掉直接使用 用来显示图片用 同步 WebAppConfig.java文件的配置
spring.path.system.default.img.file.url=file:D:/images/supermarket/

5、进行显示图片的工具类

@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
	 
 
    //访问图片方法
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       /*  String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
        if(imagesPath.indexOf(".jar")>0){
            imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
        }else if(imagesPath.indexOf("classes")>0){
            imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
        }
        imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
        SysConfigModel.defaultUrl = imagesPath;*/
        //LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath="+SysConfigModel.defaultUrl);
    	//String imagesPath = SysConfigModel.defaultFolderUrl.substring(0, SysConfigModel.defaultFolderUrl.lastIndexOf("/"))+"/";
        registry.addResourceHandler("/images/**").addResourceLocations(SysConfigModel.defaultFolderUrl);
        registry.addResourceHandler("/images/supermarket/**").addResourceLocations(SysConfigModel.defaultFolderUrl);
        registry.addResourceHandler("/images/**").addResourceLocations(SysConfigModel.defaultFileUrl);
        registry.addResourceHandler("/images/supermarket/**").addResourceLocations(SysConfigModel.defaultFileUrl);
        super.addResourceHandlers(registry);
    }  
	    
	    
}

以上是自己整理的,并测试过,可以直接用

转载声明:本文为博主原创文章,未经博主允许不得转载

⚠️注意 ~

💯本期内容就结束了,如果内容有误,麻烦大家评论区指出

如有疑问❓可以在评论区留言💬或私信留言💬,尽我最大能力🏃‍♀️帮大家解决👨‍🏫!

如果我的文章有帮助,欢迎点赞+关注✔️鼓励博主🏃,您的鼓励是我分享的动力🏃🏃🏃~​