实现uniapp点击按钮从相册选择图片上传,上传成功后返回图片的路径及URL参数

前端

使用uni自带的图片选择以及上传组件

<template>
    <view>
        <button type="default" @click="uploadImg">上传图片</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {

            }
        },
        methods: {
            uploadImg() {
                uni.chooseImage({
                    count: 1,
                    success: (res) => {
                        console.log(res)
                        uni.uploadFile({
                            url: 'http://127.0.0.1:8036/fileUpload1',
                            filePath: res.tempFilePaths[0],
                            name: 'file',
                            formData: {
                                'user': 'test'
                            },
                            success: function(uploadFileRes) {
                             console.log(uploadFileRes.data);
                            }
                        })
                    }
                })
            }
        }
    }
</script>

<style>

</style>

后端

创建一个实体类,用来返回上传完成后的文件结果

package cn.vwmwv.hgnuman.entity;

import lombok.Data;


@Data
public class UpFile {
    String pathString;
    String fileUrl;
    String msg;

}

封装一个上传文件的方法

/*
 * Copyright (c) 2022.  Kaygb
 * All rights reserved.
 * Site: https://www.vwmwv.cn/
 * Github: https://github.com/kaygb/
 */

package cn.vwmwv.hgnuman.utils;

import cn.vwmwv.hgnuman.entity.UpFile;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Random;

@Slf4j
public class UploadFile {

    public UpFile upFile( MultipartFile file){
        String basePath = new ApplicationHome(this.getClass()).getSource().getParentFile().getPath() + "/upload-files/";
        log.info(basePath);
        String pathString;
        String fileNameString;
        String file_url;
        UpFile upFile = new UpFile();
        // 检查文件是否为null以及文件类型后缀是否符合要求
        if (file != null && CheckFileType.CheckImgType(file.getContentType())) {
            // 图片后缀
            String file_suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            Random rand = new Random();
            // 图片名称
            fileNameString = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + (rand.nextInt(1000) + 1) + file_suffix;
            // 存储路径
            pathString = basePath + new SimpleDateFormat("yyyy").format(new Date()) + "/" + new SimpleDateFormat("MMdd").format(new Date()) + "/" + fileNameString;
            // 图片url
            file_url = "/upload-files/" + new SimpleDateFormat("yyyy").format(new Date()) + "/" + new SimpleDateFormat("MMdd").format(new Date()) + "/" + fileNameString;

            try {
                File files = new File(pathString); // 创建新文件
                boolean dir = files.getParentFile().exists(); //检查文件路径是否存在
                if (!files.getParentFile().exists()) { // 如果不存在则创建文件夹
                    dir = files.getParentFile().mkdirs(); // 文件夹创建结果
                }
                if (dir) {
                    file.transferTo(files); // 把文件传输到对应的位置
                    upFile.setFileUrl(file_url);
                    upFile.setPathString(pathString);
                    upFile.setMsg("");
                }else {
                    upFile.setFileUrl("error");
                    upFile.setPathString("error");
                    upFile.setMsg("文件创建失败");
                }


            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            upFile.setFileUrl("error");
            upFile.setPathString("error");
            upFile.setMsg("图片类型仅允许:jpg,jpeg,png,gif,hevc");
        }
        return upFile;
    }
}

处理路由并返回状态

    @CrossOrigin // 允许跨域
    @PostMapping("/fileUpload1")
    public Map<String, Object> fileUpload1(@RequestParam(value = "file") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        Map<String, String> upstatus = new HashMap<>();

        UploadFile uploadFile = new UploadFile();
        UpFile f = uploadFile.upFile(file);
        map.put("code", "0");
        upstatus.put("path", f.getPathString());
        upstatus.put("url", f.getFileUrl());
        map.put("data", upstatus);
        map.put("msg", f.getMsg());
        return map;
    }

测试

点击按钮上传图片,可以看到打印出来了文件在服务端存储的位置以及返回的url路径

image-20220120174939345

如果觉得我的文章对你有用,请随意赞赏