vue上传图片文件到SpringBoot简单实现

springboot代码
@RequestMapping("/uploadImgFile")
public Map<String,String> uploadImgFile(MultipartFile file,HttpServletRequest request) {
    Map<String,String> map = new HashMap<String,String>();
    try{
        String fileName = file.getOriginalFilename();
        String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
        if ("JPG".equals(type.toUpperCase())||"JPEG".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())) {
            //获取服务器名
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            // 自定义的文件名称
            String trueFileName = new Date().getTime()+"."+type;
            // 设置存放文件的路径
            String path = ResourceUtils.getURL("classpath:").getPath()+"static/img/" + trueFileName;
            File dest = new File(path);
            //判断文件父目录是否存在
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdir();
            }
            file.transferTo(dest);
            map.put("1","文件上传成功");
            map.put("imgUrl","http://"+hostAddress+":"+port+ "/img/" + trueFileName);
        }else{
            map.put("0","图片格式不对");
        }
    }catch (Exception e){
        map.put("0","文件上传失败");
    }
    return map;
}
vue代码

按钮

<button class="right-update">上传图片<input type="file" @change="selectImgChange" ref="imgfile"></button>

样式

.right-update
        height: 2rem;
        top:0.5rem;
        left:6rem;
        width:10rem;
        border:0.05rem solid #CCC;
        border-radius: 0.4rem;
        text-align: center;
        font-size: 1rem;
        font-weight:bold;
        input
            width:100%;
            height: 100%;
            position:absolute;
            left:0;
            opacity:0;
            cursor: pointer;

事件

methods: {
    selectImgChange:function(){
        let file = this.$refs.imgfile.files[0];
        var formData = new FormData();
        formData.append("file",file);
        axios({
            method:'post',
            url:this.dataUrl+"/uploadImgFile",
            data:formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(function(response){
            console.log(response.data)
        })
    }
}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值