微信小程序上传图片到服务器并返回访问链接(详细)(小程序+springboot+linux))

如果你希望把上传的图片数据存到服务器的某个文件夹下,不想存到数据库里,把访问链接存到数据库中就看下去吧

我使用的是微信小程序+springboot和linux服务器

一:大致流程

点击‘请上传图片’按钮,会把图片上传到服务器指定文件夹里,并返回可访问链接,在小程序端通过链接显示图片来确定上传图片整个流程正常,可以存取

二:具体实现

1:微信小程序端

wxml文件

 <view class='nearCard-f1'>  
    <image src='{{avator}}'></image>
    <button  bindtap='uploadAvator'>请上传图片</button>
 </view>

js文件

data:{
  //上传图片
   photoPath:'',//选择的图片路径
   avator:'../../images/photo.png',//传到服务器返回来的图片路径,引号里是默认图片

}
 uploadAvator:function(){
    var that=this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],// 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success:(res)=>{
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        console.log("tempFilePaths:"+tempFilePaths);
        that.setData({
          photoPath: tempFilePaths,
        });
        if(that.data.photoPath!=undefined){
          console.log("wx.uploadFile")
            wx.uploadFile({
              url: "https://xxxxxxx/upload", //url就是Java后台的上传图片接口,实际可以更改为自己服务器的地址。
              filePath: that.data.photoPath[0],
              name: 'file',//需要传给后台的图片字段名称
              formData: {//需要传给后台的其他表单数据
                'pdNo':that.data.pdNo
              },
              header: {
                "Content-Type": "multipart/form-data", //form-data格式
                'Accept': 'application/json', 
              },
              success: function (res) {
              console.log(res.data)
              var result=res.data
                if(res.statusCode!=200){
                  wx.showToast({
                    title: '上传失败!',
                    duration:2000
                  })
                }else{
                  var date=new Date();
                  that.setData({
                    avator:result+"?t="+date,//如果不加后缀的话第一次上传过图片之后再次上传的图片不显示,虽然图片链接已经改变,显示的仍是第一次的图片
        
                  })
                  wx.showToast({ 
                    title: '上传成功!',
                    duration:2000
                  })
                }
              },
              complete: function (res) {
                console.log(res);
              }
            })    
          }else{
            wx.showToast({
              title: '未选择照片!',
              duration:2000
            })
          }
        },
      complete: function (res) {
          console.log(res);
      }
    })
  },

wxss文件

/* 信息块1 */
.nearCard-f1 {
  width:250rpx;
  margin-left: 10rpx;
  font-size: 11rpx;
}
.nearCard-f1 image{
  width:240rpx;
  height: 240rpx;
  border-image-width: 2rpx;
  border-color: #666;
  margin-top: 10rpx;
  border:1rpx solid #ccc;
  border-radius: 10rpx;
  z-index: 3;
}
.nearCard-f1 button{
  width:180rpx;
  height:60rpx;
  font-size: 25rpx;
  margin-top: 4rpx;
  padding: 0rpx;
}

2:springboot端

(1)application.properties

如果上传到本地计算机文件夹

##这里选择文件夹作为对外访问的目录,可以根据具体需求设置
upload-path=G:/images/
##表示所有的访问都经过静态资源路径
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath\:/META-INF/resources/,classpath\:/resources/,classpath\:/static/,classpath\:/public/,file\:${web.upload-path}
classpath:/static/,classpath:/public/,file:${upload-path}

       如果上传到linux服务器文件夹

##这里选择文件夹作为对外访问的目录,可以根据具体需求设置
upload-path=/home/images/

(2)配置类

/**
 * @author Administrator
 * @title: UploadFileConfig
 * @description: TODO
 * @date 2020-11-1116:39
 */
@Configuration
public class UploadFileConfig extends WebMvcConfigurationSupport {
    @Value("${upload-path}")
    private  String path;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        /**
         * 配置资源映射
         * 意思是:如果访问的资源路径是以“/images/”开头的,
         * 就给我映射到path这个文件夹内,去找你要的资源
         **/
        registry.addResourceHandler("/images/**").
                addResourceLocations("file:"+path);
        System.out.print("上传配置类path="+path+"\n");
        super.addResourceHandlers(registry);

    }

}

(3)controller控制层

/**
      * @description: 图片上传
      * @date 2020-11-17 16:13
      */
    @Value("${upload-path}")
    private String realPath;

    @ResponseBody
    @RequestMapping(value ="upload", method = RequestMethod.POST)
//    图片是以content-type为multipart/form-data的格式上传的,所以使用spring-mvc可以通过使用参数的形式以二进制的格式获取到该图片。
    public String upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        System.out.println("执行upload");
        request.setCharacterEncoding("UTF-8");
        log.info("执行图片上传");
        String pdNo = request.getParameter("pdNo");
        log.info("pdNo:"+pdNo);
        String path ;
        String type ;
        String avator;
        if(!file.isEmpty()) {
            log.info("成功获取照片");
            String fileName = file.getOriginalFilename();
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            log.info("图片初始名称为:" + fileName + " 类型为:" + type);
            if (type != null) {
                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {

                    log.info("图片根路径:"+realPath);
                    // 自定义的文件名称
                    Calendar rightNow=Calendar.getInstance();
                    Integer year = rightNow.get(Calendar.YEAR);
                    Integer month = rightNow.get(Calendar.MONTH)+1; //第一个月从0开始,所以得到月份+1
                    Integer day = rightNow.get(rightNow.DAY_OF_MONTH);

                    String date="("+year+"-"+month+"-"+day+")";
//                    String trueFileName =pdNo+"-"+date+fileName.substring(fileName.lastIndexOf("."));
                    String trueFileName =pdNo+"-"+date+".jpg";//把图片都变成jpg格式,按需求决定该不该格式
                    log.info("图片自定义名称为:" + trueFileName + " 类型为:" + type);
                    // 设置存放图片文件的路径
                    path = realPath +trueFileName;
                    log.info("存放图片文件的路径:" + path);
                    //判断文件父目录是否存在
                    File dest=new File(path);
                    if(!dest.getParentFile().exists()){
                        dest.getParentFile().mkdir();
                    }
                    //保存文件
                    file.transferTo(new File(path));
                    log.info("文件成功上传到指定目录下");
                    avator=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + trueFileName;
                    log.info("数据库存放图片文件的路径:" + avator);
                }else {
                    log.info("不是我们想要的文件类型,请按要求重新上传");
                    return "error";
                }
            }else {
                log.info("文件类型为空");
                return "error";
            }
        }else {
            log.info("没有找到相对应的文件");
            return "error";
        }
        return avator;//返回图片访问路径,可以把这个连接存到数据库里,小程序端以后就可以直接访问图片了
    }

}

学会了就赶紧去试试吧!

完结;

  • 3
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值