springboot + uniapp 实现单文件上传及图片回显

一、使用 uni-file-picker 组件标签

具体使用方法请查看 uniapp 官网 uni-file-picker 的介绍。

前端代码

代码如下,通过 uni.uoloadFile 上传到后端返回 url 地址赋值 value 进行图片回显。

<template>
	<view class="container">
		<uni-file-picker file-mediatype="image" mode="grid" @select="select" />
		<!-- 图片上传 -->
		<image :src="value" mode=""></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
                value: ''
			}
		},
		methods: {
			select(e) {
				uni.uploadFile({
					url: `http://localhost:5050/files/file`,//你后端服务器地址
					filePath: e.tempFilePaths[0],//要上传文件资源的路径
					name: 'file',//文件对应的名称,与后端接收的属性名一直 
					formData: {},//请求中其他额外的数据
					success: (uploadFileRes) => {
						this.value = uploadFileRes.data;
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	.container {
		width: 100%;
		height: 100%;
		background-color: #fff;
		position: fixed;
	}
</style>

后端代码

首先是 application.yml 配置文件,端口号配置的 5050,根据你的需求更改。

自定义文件的存放位置:file:path: D://uploadPath/images/

# 端口号
server:
  port: 5050
spring:
  # 文件上传配置
  servlet:
    multipart:      
      #是否开启文件上传支持,默认是 true
      enabled: true
      #文件写入磁盘的阈值,默认是0
      file-size-threshold: 0
      # 设置单个文件的最大尺寸
      max-file-size: 10MB
      # 设置请求的最大尺寸
      max-request-size: 100MB
# 自定义图片存放位置
file:
  path: D://uploadPath/images/

controller 控制层代码

package com.test.blog.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/files")
public class FilesUnloadController {
    // 文件上传路径
    @Value("${file.path}")
    private String filePath;

    // 单文件上传
    @RequestMapping("/file")
    public String upload(@RequestParam MultipartFile file, HttpServletRequest request) {
        // 获取服务器路径
        String serverPath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort();
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 保存文件
        File newFile = new File(filePath + '\\' + fileName);
        // 获取文件url
        String url = serverPath + "/images/" + fileName;
        // 判断父级文件目录是否存在,不存在则创建
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
            System.out.println("父级文件目录不存在,已创建目录");
        }
        try {
            // 保存文件
            file.transferTo(newFile);
            System.out.println("文件上传成功");
        } catch (IOException e) {
            // 程序错误
            e.printStackTrace();
            System.out.println("程序错误,请重新上传");
        }
        // 返回文件 url
        return url;
    }
}

添加一个配置类,将静态文件映射位置映射出去,可以通过 url 访问。

package com.test.blog.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
	// 设置静态资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("file:D:/uploadPath/images/");
    }
}

二、使用 uni.chooseImage 接口

通过 uni.chooseImage 接口获取到一个本地资源的临时文件路径后,可通过此接口将本地资源上传到指定服务器。

具体使用方法请查看 uniapp 官网 uni.chooseImage 的介绍。

后端代码与(一)中一致,前端代码如下:

<template>
	<view class="container">
		<!-- 图片上传 -->
		<image :src="value" mode=""></image>
		<button @click="uploadFile">图片上传</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				value: ''
			}
		},
		methods: {
			uploadFile() {
                //从本地相册选择图片或使用相机拍照。
				uni.chooseImage({
					success: (chooseImageRes) => {
                        uni.uploadFile({
							url: `http://localhost:5050/files/file`,//你后端服务器地址
							filePath: chooseImageRes.tempFilePaths[0],//要上传文件资源的路径
							name: 'file',//文件对应的名称,与后端接收的属性名一直 
							formData: {},//请求中其他额外的数据
							success: (uploadFileRes) => {
								this.value = uploadFileRes.data;
							}
						});
					}
				});
			},	
		}
	}
</script>

<style lang="scss">
	.container {
		width: 100%;
		height: 100%;
		background-color: #fff;
		position: fixed;
	}
</style>
实现uniapp拍照转文字回显的功能,可以借助uni-app插件uni-ocr,该插件提供了图片识别和文字识别的功能。 以下是实现步骤: 1. 安装uni-ocr插件,可以通过npm install uni-ocr命令进行安装。 2. 在页面中添加拍照按钮和图片显示区域,如下所示: ``` <view> <button type="primary" @click="takePhoto">拍照</button> <image v-if="imageUrl" :src="imageUrl"></image> <text v-if="ocrText">{{ ocrText }}</text> </view> ``` 3. 在页面的<script>标签中定义变量和方法,如下所示: ``` <script> import uniOcr from '@/uni_modules/uni-ocr/js_sdk/uni-ocr.js'; export default { data() { return { imageUrl: '', ocrText: '' } }, methods: { takePhoto() { uni.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['camera'], success: (res) => { this.imageUrl = res.tempFilePaths[0]; this.recognizeText(); } }); }, recognizeText() { uniOcr.recognizeText({ path: this.imageUrl, success: (res) => { console.log(res); this.ocrText = res.text; }, fail: (err) => { console.log(err); } }); } } } </script> ``` 4. 在takePhoto方法中,调用uni.chooseImage方法选择拍摄照片,将照片路径存储在imageUrl变量中,并调用recognizeText方法进行文字识别。 5. 在recognizeText方法中,调用uni-ocr插件的recognizeText方法进行文字识别,识别成功后将识别的文本存储在ocrText变量中,并在页面中显示。 注意:为了使用uni-ocr插件,需要在manifest.json文件中配置权限,具体配置方法可以参考uni-ocr官方文档。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你的柠檬我的心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值