微信小程序图片上传到SpringBoot到阿里云OSS然后返回一个url

一、微信小程序部分代码

1.wxml

<view class="container">
  <button bindtap="chooseMedia" type="primary">选择图片</button>
  <input bindinput="inputText" placeholder="请输入文字" />
  <button bindtap="uploadData" type="primary">上传</button>
  <view wx:if="{{uploadTime}}">上传时间: {{uploadTime}}</view>
//展示图片
  <view wx:if="{{mediaUrls.length > 0}}">
    <view wx:for="{{mediaUrls}}" wx:key="{{index}}">
      <image src="{{item}}" mode="aspectFill" />
    </view>
  </view>
</view>

2.wxss

注:自己修改样式

.container {
  margin-top: 20px;
  text-align: center;
}

3.js

注:要把text文本放在wx.uploadFile的formData属性里面,会当做form表单形式提交文本

Page({
  data: {
    mediaUrls: [], // 保存选择的图片的临时路径列表
    text: '', // 保存输入的文字
    uploadTime: '', // 保存上传时间
  },
  chooseMedia: function () {
    wx.chooseMedia({
      count: 9 - this.data.mediaUrls.length, // 最多选择9张图片
      mediaType: ['image'],
      success: (res) => {
        const tempFilePaths = res.tempFiles.map((file) => file.tempFilePath); // 获取选择的图片的临时路径列表
        this.setData({
          mediaUrls: this.data.mediaUrls.concat(tempFilePaths), // 添加到已选择的图片列表中
        });
      },
    });
  },
  inputText: function (e) {
    this.setData({
      text: e.detail.value, // 获取输入的文字
    });
  },
  uploadData: function () {
    const uploadTime = new Date().toLocaleString(); // 获取当前时间
    this.setData({
      uploadTime: uploadTime, // 设置上传时间
    });

    const uploadPromises = this.data.mediaUrls.map((mediaUrl) => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'http://localhost:9000/upload', // 替换为你的Spring Boot服务器的URL
          filePath: mediaUrl, // 上传选择的图片
          name: 'files',
          formData: {
            text: this.data.text, // 上传输入的文字
            uploadTime: uploadTime, // 上传时间
          },
          success: (res) => {
            resolve(res.data); // 上传成功后的响应数据
            console.log(this.data.mediaUrls);
          },
          fail: (error) => {
            reject(error);
          },
        });
      });
    });

    Promise.all(uploadPromises)
      .then((results) => {
        console.log("chenggong");
        console.log(results); // 所有图片上传成功后的响应数据
      })
      .catch((error) => {
        console.log(error); // 上传失败的错误信息
      });
  },
});

二、SpringBoot

1.OSSUtil工具类

package com.mz.auth.util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;

@Component
public class OSSUtil {
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.file.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.file.bucketName}")
    private String bucketName;
    public String handleImageUpload(MultipartFile file) {
        // 获取上传的文件名
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        // 你可以根据自己的需求将文件保存到指定的位置
        
        // 生成新的文件名,避免文件名冲突
        String newFileName = "test/"+UUID.randomUUID().toString() + "_" + fileName;
        try {
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId, accessKeySecret);

            // 上传文件到阿里云OSS
            ossClient.putObject(bucketName, newFileName, file.getInputStream());
            System.out.println("1234");
            // 关闭OSSClient
            ossClient.shutdown();

            // 返回文件在OSS中的访问URL
            System.out.println("https://" + bucketName + "." + endpoint + "/" + newFileName);
            return "https://" + bucketName + "." + endpoint + "/" + newFileName;
        } catch (IOException e) {
            System.out.println("cc");
            e.printStackTrace();
            return null;
        }
    }
}

2.OSSController

package com.mz.auth.web.controller;

import com.mz.auth.util.OSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class OssController {
    @Autowired
    private OSSUtil ossUtil;


    @PostMapping("/upload")
    public void handleImageUpload(@RequestParam("files") MultipartFile[] files, @RequestParam("text") String text, @RequestParam("uploadTime") String uploadTime) {
        for (MultipartFile file:files){
            System.out.println(ossUtil.handleImageUpload(file));
        }



}}

3.配置文件

aliyun.oss.file.endpoint=oss-cn-guangzhou.aliyuncs.com
aliyun.oss.file.bucketName=
aliyun.oss.file.accessKeyId=
aliyun.oss.file.accessKeySecret=

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的微信小程序图片上传阿里云OSS的例子: 1. 在微信小程序中,使用wx.chooseImage()方法选择需要上传的图片,并将其保存在本地变量tempFilePaths中。 ``` wx.chooseImage({ success: function(res) { var tempFilePaths = res.tempFilePaths; // 上传图片到阿里云OSS uploadImage(tempFilePaths[0]); } }) ``` 2. 编写上传图片的函数uploadImage(),其中需要设置header、formData、name、url等参数,并调用wx.uploadFile()方法上传图片。 ``` function uploadImage(filePath) { // 阿里云OSS的Bucket名称和上传文件夹名称 var bucketName = 'your-bucket-name'; var folderName = 'your-folder-name/'; // 生成上传文件的唯一key var timestamp = new Date().getTime(); var key = folderName + timestamp + '-' + Math.floor(Math.random() * 10000) + '.jpg'; // 生成OSS的上传接口地址 var policyBase64 = 'your-policy-base64'; var signature = 'your-signature'; var aliyunUrl = 'https://' + bucketName + '.oss-cn-hangzhou.aliyuncs.com'; // 设置header和formData var header = { 'content-type': 'multipart/form-data' }; var formData = { 'key': key, 'policy': policyBase64, 'OSSAccessKeyId': 'your-access-key-id', 'success_action_status': '200', 'signature': signature }; // 调用wx.uploadFile()方法上传图片 wx.uploadFile({ url: aliyunUrl, filePath: filePath, name: 'file', header: header, formData: formData, success: function(res) { // 上传成功,获取图片URL地址 var imageUrl = aliyunUrl + '/' + key; console.log('上传成功,图片URL地址为:' + imageUrl); }, fail: function(res) { // 上传失败 console.log('上传失败:' + res.errMsg); } }) } ``` 需要注意的是,以上代码仅为一个示例,实际使用时需要按照阿里云OSS的规定进行设置,并在后端服务中编写相应的签名验证逻辑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值