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

Springboot + Vus.js整合阿里云OSS进行图片上传的操作(前后端结合)

程序员文章站 2022-07-10 10:39:40
...

一般来讲,我们在进行后端开发的时候,图片、文件之类的上传是十分头疼的。但是现在有比如七牛云、阿里云OSS等图片、文件上传方案之后,我们处理文件上传的方式变得极为简便。使用阿里云OSS进行图片上传之后我们就可以直接得到我们的上传的文件、图片的url路径。

我们先来看一下我们后端的OSSClientUtils文件上传所需要的工具代码
package com.logistics.utils;

import com.aliyun.oss.OSSClient;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

public class OSSClientUtils {

    private static String endpoint = "###这里写endpoint值###";
    private static String accessKeyId = "###这里写accessKeyId值###";
    private static String accessKeySecret = "###这里写accessKeySecret值###";

    public static String putAppImg(String name, byte[] data) {
        String bucket = "###这里写bucket值###";
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        InputStream is = new ByteArrayInputStream(data);
        client.putObject(bucket, name, is);
        client.shutdown();
        // 这里写自己的https路径
        return "https://#######.com/" + name;
    }

    public static String putFile(String name, byte[] data) {
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String bucket = "###这里写bucket值###";
        InputStream is = new ByteArrayInputStream(data);
        client.putObject(bucket, name, is);
        client.shutdown();
        // 这里写自己的https路径
        return "https://######.com/" + name;
    }

    public static String putAppImg(String name, File file) {
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String bucket = "###这里写bucket值###";
        client.putObject(bucket, name, file);
        client.shutdown();
        // 这里写自己的https路径
        return "https://######.com/" + name;
    }

}
随后我们来写我们Controller层可以直接调用的这个utils工具类
package com.logistics.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 工具类
 */
public class CommonUtils {

    public static String createIdcode() {
        long time = System.currentTimeMillis();
        String idcode = letterize(time);
        return idcode;
    }

    public static String letterize(long number) {
        String letters = "0123456789abcdefghijklmnopqrstuvwxyz";
        int abcsLen = letters.length();
        StringBuffer buffer = new StringBuffer();
        do {
            long a = number / abcsLen;
            long b = number % abcsLen;
            buffer.append(letters.charAt((int) b));
            number = a;
        } while (number > 0);
        buffer.reverse();
        return buffer.toString();
    }

    public static String getNowString(String ff) {
        SimpleDateFormat format = new SimpleDateFormat(ff);
        Date now = new Date();
        String created = format.format(now);
        return created;
    }

    public static String getFileExtName(String filename) {
        return filename.substring(filename.lastIndexOf(".")).toLowerCase();
    }

    /**
     * 上传文件/图片都可以,最后返回超链接路径 (主用)
     * @param mf
     * @return
     */
    public static String uploadFile(MultipartFile mf) {
        String ofn = mf.getOriginalFilename();
        String ext = getFileExtName(ofn);
        String daystr = getNowString("yyyyMMdd");
        String filename = String.format("athena/%s/%s%s", daystr, createIdcode(), ext);
        try {
            String fileurl = OSSClientUtils.putFile(filename, mf.getBytes());
            return fileurl;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将网络图片保存到阿里云oss
     **/
    public static String savePicture(String urlHttp){
        String picPath = null;
        try {
            File tmpFile = File.createTempFile(CommonUtils.createIdcode(), ".png");
            URL url = new URL(urlHttp);
            BufferedImage img = ImageIO.read(url);
            String tempFilePath = tmpFile.getAbsolutePath();
            tmpFile.delete();
            ImageIO.write(img, "png", new File(tempFilePath));
            String daystr = getNowString("yyyyMMdd");
            String ext = ".png";
            String filename = String.format("athena/%s/%s%s", daystr, createIdcode(), ext);
            picPath = OSSClientUtils.putAppImg(filename,tmpFile);
            tmpFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return picPath;
    }

}
后端的最后一步就是拟写我们的Controller层代码接收前端传过来的文件
@Api(description = "图片/文件上传的接口")
@RestController
@RequestMapping("/upload")
public class UploadController {

    /**
     * 图片上传接口
     *
     * @return
     */
    @ApiOperation(value = "图片/文件 上传接口", httpMethod = "POST")
    @PostMapping("/uploadFile")
    public ResultJson uploadFile(@RequestParam("upload") MultipartFile upload){
        String path = CommonUtils.uploadFile(upload);
        System.out.println("图片url路径:" + path + "");
        return ResultJson.ok(path);
    }

}

随后我们来看一下前端的处理部分

HTML部分代码

<label for="idCardOne">身份证正面照:</label>
                <div class="input-group mb-3">
                    <input @change="uploadCardOne($event)" v-model="idCardOne" type="file" class="form-control" id="idCardOne" name="upload">
                    <div class="input-group-append">
                        <span class="input-group-text">@runoob.com</span>
                    </div>
                </div>

                <label for="idCardTwo">身份证反面照:</label>
                <div class="input-group mb-3">
                    <input @change="uploadCardTwo($event)" v-model="idCardTwo" type="file" class="form-control" id="idCardTwo" name="upload">
                    <div class="input-group-append">
                        <span class="input-group-text">@runoob.com</span>
                    </div>
                </div>

Vue.js部分代码

new Vue({
    el:"#app",
    data:{
      idCardOne:"",               //身份证正面
      idCardTwo:""                //身份证反面
    },
    methods:{
    	uploadCardOne:function(event){
            //获取图片
            var _this = this;
            _this.idCardOne = event.target.files[0];

            //上传图片
            event.preventDefault();

            var formData = new FormData();
            // 注意这里的upload要对应前端中的input框的name的值
            formData.append('upload', _this.idCardOne);

            var config = {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
            axios.post('/logisticsSystem/upload/uploadFile',formData,config)
                .then(function (response) {
                    if (response.data.code == 1) {
                        alert("身份证正面照上传" + response.data.msg);
                        _this.idCardOne = response.data.data;
                        alert("idCardOne:" + _this.idCardOne);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                })
        },
        uploadCardTwo:function(event){
            //获取图片
            var _this = this;
            _this.idCardTwo = event.target.files[0];

            //上传图片
            event.preventDefault();

            var formData = new FormData();
            // 注意这里的upload要对应前端中的input框的name的值
            formData.append('upload', _this.idCardTwo);

            var config = {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
            axios.post('/logisticsSystem/upload/uploadFile',formData,config)
                .then(function (response) {
                    if (response.data.code == 1) {
                        alert("身份证反面照上传" + response.data.msg);
                        _this.idCardTwo = response.data.data;
                        alert("idCardTwo:" + _this.idCardTwo);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                })
        }
    }
});

Springboot + Vus.js整合阿里云OSS进行图片上传的操作(前后端结合)


展示部分的前端代码

<label for="idCardOne">身份证正面照:</label>
            <div class="input-group mb-3">
                <img id="idCardOne" style="width: 500px;height: 350px;" v-bind:src="orders.idCardOne">
                <div class="input-group-append">
                    <span class="input-group-text">正面照</span>
                </div>
            </div>

            <label for="idCardTwo">身份证反面照:</label>
            <div class="input-group mb-3">
                <img id="idCardTwo" style="width: 500px;height: 350px;" v-bind:src="orders.idCardTwo">
                <div class="input-group-append">
                    <span class="input-group-text">反面照</span>
                </div>
            </div>

效果图
Springboot + Vus.js整合阿里云OSS进行图片上传的操作(前后端结合)