主要是通过微信小程序将图片上传到Spring boot所在服务器并保存,保存成功后返回图片名称,小程序根据图片名称,远程显示图片,小程序的代码在前面的博文中微信小程序canvas实现个人签名,并保存为图片。
Spring boot controller部分代码如下:
package com.example.refi.controller;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@RestController
@EnableAutoConfiguration
public class FileCOntroller {
/**
* 上传图片
* @param file 图片文件
* @return 上传状态或图片名称
*/
@PostMapping("/uppic")
public String getFile(@RequestParam("file") MultipartFile file) {
System.out.println("收到请求");
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
String fileName = file.getOriginalFilename();
String filePath = "C:\\Users\\96589\\Pictures\\";
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
System.out.println("上传成功");
return fileName;
} catch (IOException e) {
System.out.println("上传失败");
System.out.println(e.getMessage());
}
return "上传失败!";
}
/**
* 根据图片名称返回本地图片
* @param name 图片名称
* @return 返回本地图片
*/
@GetMapping(value = "/pic", produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] getPicture(@RequestParam("name") String name) {
System.out.println("请求图片");
String filePath = "C:\\Users\\96589\\Pictures\\";
File file = new File(filePath + name);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return bytes;
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return null;
}
}