准备
- 确定好服务器端文件保存的位置
- 确定好请求参数名(前后端要保持一致的喔)
- 如果手机是通过
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)addFormDataPart("file", imageFile!!.name, RequestBody.create(MediaType.parse("image
服务端(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;@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;}}
}
运行调试即可…