当前位置: 首页 > news >正文

Android端上传文件到Spring Boot后端

准备

  • 确定好服务器端文件保存的位置
  • 确定好请求参数名(前后端要保持一致的喔)
  • 如果手机是通过usb连接到电脑的,需要执行一下:
    • adb reverse tcp:8080 tcp:8080
  • AndroidManifest.xml<application/>节点中加上:
    • android:usesCleartextTraffic="true"
  • 引入依赖:
    • implementation("com.google.net.cronet:cronet-okhttp:0.1.0")

开始

Android端

Activity(ComponentActivity)private lateinit var imagePicker: ActivityResultLauncher<PickVisualMediaRequest>override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)imagePicker = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) {context.contentResolver.openInputStream(it)?.use {val file = File(File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "TempFiles").smartCreate(true), "Image_${currentTimeMillis}.png").smartCreate()it.copyTo(FileOutputStream(file))launch(Dispatchers.Main) { launch(Dispatchers.IO) { val clint = OkHttpClient()val requestBody = MultipartBody.Builder().apply {setType(MultipartBody.FORM)// 这个 "file" 是前后端参数名,保持一致,不然springboot报错addFormDataPart("file", imageFile!!.name, RequestBody.create(MediaType.parse("image/*"),imageFile))}.build()val responseBody = clint.newCall(Request.Builder().post(requestBody).url("http://localhost:8080/upload").build()).execute().body()logE { "${responseBody?.string()}" }}}}}
}inline val currentTimeMillis: Longget() = System.currentTimeMillis()fun File.smartCreate(isDir: Boolean = false): File {if (!exists()) {parentFile?.mkdirs()if (isDir) mkdir() else createNewFile()}return this
}

服务端(Spring Boot)

1.在application.properties文件中配置文件相关的参数

spring.servlet.multipart.max-request-size=50MB
spring.servlet.multipart.max-file-size=50MB# 上传的文件保存在哪个文件下,这里保存到项目文件夹下的upload文件夹
# 也可以指定其他文件夹,把路径复制上就行,比如 upload.file.path=C:\Users\Public\Pictures
upload.file.path=upload

2.写Controller方法

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;@RestController
public class TestController {@Value("${upload.file.path}")private String uploadPathStr;/*** 保持请求参数名一致* * @param file* @return*/@PostMapping("/upload")public @ResponseBody boolean upload(@RequestParam("file") MultipartFile file){if(file == null || file.isEmpty() || filename == null || filename.isEmpty())return false;try(InputStream inputStream = file.getInputStream()) {Path uploadPath = Paths.get(uploadPathStr);if(!uploadPath.toFile().exists())uploadPath.toFile().mkdirs();Files.copy(inputStream, Paths.get(uploadPathStr).resolve(file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);System.out.println("upload file , filename is "+file.getOriginalFilename() + ", filePath = " + Paths.get(uploadPathStr).resolve(file.getOriginalFilename()).toAbsolutePath().toString());return true;}catch (IOException e) {e.printStackTrace();return false;}}
}

运行调试即可…

http://www.lryc.cn/news/95193.html

相关文章:

  • 使用GGML和LangChain在CPU上运行量化的llama2
  • 微服务基础理论
  • 《向量数据库指南》:向量数据库Pinecone管理数据教程
  • 以深度为基础的Scikit-learn: 高级特性与最佳实践
  • Autosar MCAL-S32K324Dio配置-基于EB
  • 【Spring Boot】单元测试
  • Flink CEP (一)原理及概念
  • vue3+taro+Nutui 开发小程序(二)
  • Transformer 模型实用介绍:BERT
  • Spring详解(学习总结)
  • 【JavaEE】Spring中注解的方式去获取Bean对象
  • 【基于CentOS 7 的iscsi服务】
  • 解决安装依赖时报错:npm ERR! code ERESOLVE
  • 98、简述Kafka的rebalance机制
  • 【人工智能】监督学习、分类问题、决策树、信息增益
  • Pytorch迁移学习使用Resnet50进行模型训练预测猫狗二分类
  • HTML与XHTML的不同和各自特点
  • 微服务如何治理
  • 一本通1919:【02NOIP普及组】选数
  • Kubernetes 集群管理和编排
  • DDS协议--[第六章][Discovery]
  • 如何设置iptables,让网络流量转发给内部容器mysql
  • 数字IC实践项目(7)—CNN加速器的设计和实现(付费项目)
  • 基于深度学习的高精度80类动物目标检测系统(PyTorch+Pyside6+YOLOv5模型)
  • 海康摄像头开发笔记(一):连接防爆摄像头、配置摄像头网段、设置rtsp码流、播放rtsp流、获取rtsp流、调优rtsp流播放延迟以及录像存储
  • 【NCNN】NCNN中Mat与CV中Mat的使用区别及相互转换方法
  • Android 13 设置自动进入wifi adb模式
  • (笔记)插入排序
  • 结构型模式 - 组合模式
  • EDM营销过时了?不,这才是跨境电商成功的最佳工具