欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信小程序图片预览及上传至后台(JAVA)

程序员文章站 2024-02-26 17:49:04
...

技术小白一枚,如有出现错误的地方,还请各位多加指点,也欢迎前来交流。

微信小程序上传图片,进行预览并上传至后台。

1、效果图

微信小程序图片预览及上传至后台(JAVA)
微信小程序图片预览及上传至后台(JAVA)

2、小程序前端

1)WXML文件

<!--pages/user/edit/record_edit/record_edit.wxml-->
<view class="section">
	<picker mode="date" value="{{date}}" start="2020-05-31" end="2030-05-31" bindchange="bindDateChange">
		<text decode="{{true}}" class="date">日期&nbsp;:&nbsp;&nbsp;</text>
    <view class="picker" >{{dates}}</view>
	</picker>
</view>
<view class="textarea">
	<textarea placeholder="发条记录吧~" class="textinput" placeholder-style="color:#888888; font-size:36rpx;" maxlength="-1" bindinput="bingTextAreaBlur" value="{{detail}}"></textarea>
  <view>
  <image class="del" data-id="{{itemName.id}}" src="../../../../images/x.png" mode="widthFix" bindtap="delete" wx:if="{{img}}" ></image>
  <image class="img" src='{{img}}' mode="widthFix" wx:if="{{img}}"></image>
  </view>
  <view><image src="../../../../images/img.png" bindtap="upimg" class="upimg" mode="widthFix"></image></view>
</view>
<view class="big-logos">
</view>
<view id="btn" class="click" bindtap="send">完 成</view>

2)WXSS文件

/* pages/user/edit/record_edit/record_edit.wxss */
page {
  left: 0rpx;
  right: 0rpx;
  height: 100%;
  background-color: #FFD150;
}
.section{
  margin:20rpx;
  padding:20rpx
}
.date{
  font-weight: bold;
  float: left;
}
.picker{
  width: 82%;
  height: 50rpx;
  background-color: white;
  margin-left: 20%;
  text-align: center;
  border-radius: 25rpx;
  font-weight: bold;
}
.img{
  width: 400rpx;
}
.textarea{
  width: 90%;
  background-color: white;
  padding: 2%;
  margin-left: 3%;
  border: 2rpx solid #BBBBBB;
  border-radius: 20rpx;
}
.click{
  width: 94%;
  height: 60rpx;
  line-height: 60rpx;
  /* font-weight: bold; */
  margin-top: 3%;
  background-color: white;
  margin-left: 3%;
  text-align: center;
  border-radius: 20rpx;
}
.textinput{
  min-height: 180rpx;
  height: auto;
}
.upimg{
  width: 70rpx;
  position: relative;
}
.del {
  width: 55rpx;
  height: 55rpx;
  position: absolute;
  left: 52%;
}

3)JS文件

// pages/user/edit/record_edit/record_edit.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dates: '2020-05-31',
    img_arr: '',
    img: '',
    detail: '',
    id: 0,
  },

  //点击日期组件确定事件  
  bindDateChange: function (e) {
    // console.log(e.detail.value)
    this.setData({
      dates: e.detail.value
    })
  },
  
  //获取textarea内容
  bingTextAreaBlur: function (e) {
    this.data.detail = e.detail.value
  },

  //删除图片
  delete: function (e) {
    var that = this;
    that.setData({
      img: ''
    });
  },
  //上传图片
  upload: function () {
    var that = this
    // console.log(getApp().globalData.role + ' | ' + that.data.dates + ' | ' + that.data.detail + ' | ' + that.data.img)
    wx.uploadFile({
      url: getApp().globalData.server + '/record/uploadImg', //自己的接口地址
      filePath: that.data.img,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data",
        'accept': 'application/json',
      },
      formData: ({ //上传图片所要携带的参数
        role: getApp().globalData.role,
        timestamp: that.data.dates,
        detail: that.data.detail,
        id: that.data.id,
      }),
      success(res) {
        // console.log(res.statusCode)
        if (res.statusCode != 200) {
          wx.showModal({
            title: '提示',
            content: "上传失败",
            showCancel: false,
            success(res) {}
          })
        } else {
          wx.showModal({
            title: '恭喜',
            content: '小记录发布成功',
            showCancel: false,
            success(res) {},
            complete: function (res) {
              wx.navigateBack({
                success: function (e) {
                  var page = getCurrentPages().pop();
                  if (page == undefined || page == null) return;
                  page.onLoad();
                }
              })
            }
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '哎呀',
          content: '网络不在状态呢~',
          showCancel: false,
          success(res) {}
        })
      },
      complete: function (res) {
        wx.hideLoading()
      }
    })
  },
  
  //图片预览
  upimg: function () {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        that.setData({
          img: that.data.img_arr.concat(res.tempFilePaths)
        });
      }
    })
    // console.log(that.data.img)
  },
  
  //上传小记录
  send: function (e) {
    var that = this
    // console.log(that.data.img + ',')
    wx.showLoading({
      title: '加载中',
    })

    // console.log(','+that.data.img+',')
    //判断图片是否为空
    if (that.data.img != null && that.data.img.length != 0) {
      that.upload();
    } else {
      //与服务器交互
      console.log(that.data.img)
      wx.request({
        url: getApp().globalData.server + '/record/addRecord', //接口地址
        data: {
          role: getApp().globalData.role,
          timestamp: that.data.dates,
          detail: that.data.detail,
          id: that.data.id,
          pic: that.data.img
        },
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success(res) {
          if (res.data.error_code != 0) {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false,
              success(res) {}
            })
          } else if (res.data.error_code == 0) {
            wx.showModal({
              title: '恭喜',
              content: res.data.msg,
              showCancel: false,
              success(res) {},
              complete: function (res) {
                wx.navigateBack({
                  success: function (e) {
                    var page = getCurrentPages().pop();
                    if (page == undefined || page == null) return;
                    page.onLoad();
                  }
                })
              }
            })
          }
        },
        fail: function (res) {
          wx.showModal({
            title: '哎呀',
            content: '网络不在状态呢~',
            showCancel: false,
            success(res) {}
          })
        },
        complete: function (res) {
          wx.hideLoading()
        }
      })
    }

    setTimeout(function () {
      wx.hideLoading()
    }, 2000)
  },
})

3、后台(JAVA-SpringBoot)

1)图片传入位置

image文件夹是自己创建的,图片将传进image中。
微信小程序图片预览及上传至后台(JAVA)

2)接收并上传图片

//如果只是要传图片,仅看addRecord中的下面两行与UploadPictures即可
String fileName = file.getOriginalFilename();
commonService.UploadPictures(file, fileName);

---------------------------------addRecord方法--------------------------------------
@RequestMapping("/uploadImg")
public int addRecord(MultipartFile file, int role, String detail, String timestamp, int id) throws IOException {
        int flag = 0;
        String fileName = file.getOriginalFilename();
        commonService.UploadPictures(file, fileName);
        RecordBean recordBean = new RecordBean(id, role, detail, fileName, timestamp);
        if(id==0){
            if (recordService.addRecord(recordBean) > 0) {
                flag = 1;
            }
        }else{
            if (recordService.updateRecord(recordBean) > 0){
                flag = 1;
            }
        }
        return flag;
    }
    
---------------------------------UploadPictures方法------------------------------------
//将文件写入磁盘
    public void UploadPictures(MultipartFile file, String fileName) throws IOException {
        String filePath = ResourceUtils.getURL("image").getPath()+"/";
        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(filePath + fileName)));
            bufferedOutputStream.write(bytes);
            bufferedOutputStream.close();
        }
    }
相关标签: 小程序 java