The upload component of antd uploads pictures to the resource folder of the backend project
front end
<Upload name=“logo” action=“http://localhost:9001/api/phonebook/uploadPhoto” listType=“picture”
accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
maxCount={1} {…props}>
<Button icon={}>点击上传
<Form.Item
name="photo"
label="照片"
valuePropName="fileList"
getValueFromEvent={
normFile}
extra="请上传照片"
>
<Upload name="logo" action="http://localhost:9001/api/phonebook/uploadPhoto" listType="picture"
accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
maxCount={
1} {
...props}>
<Button icon={
<UploadOutlined />}>点击上传</Button>
</Upload>
</Form.Item>
- accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG", for restricted file formats
- maxCount={1}, to limit the number of uploaded files, when =1, the newest overwrites the previous
- name="logo", the name obtained by the backend
- action="http://localhost:9001/api/phonebook/uploadPhoto" is the backend api interface
To get the return value, check the change function in the official document, info.file.responce to get
backend part
@RequestMapping("/uploadPhoto")
@ResponseBody
public Map<Integer,String> uploadPhoto(@RequestParam("logo") MultipartFile pic) throws IOException {
/*
* 编码为字符串*/
String s = Base64Utils.encodeToString(pic.getBytes());
System.out.println("s:"+s);
/* *
*2.解码成字节数组
*/
Base64.Decoder decoder = Base64.getDecoder();
byte[] bytes = decoder.decode(s);
System.out.println("by:"+s);
/*
* 3.字节流转文件
*/
String d = System.getProperty("user.dir");
File fileMkdir = new File(d+"\\src\\main\\resources\\img");
if (!fileMkdir.exists()){
fileMkdir.mkdir();
}
String pathName = fileMkdir.getPath() + "\\" + pic.getOriginalFilename();
System.out.println("path"+pathName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pathName);
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
HashMap<Integer,String> need = new HashMap<>();
need.put(0,"img\\"+ pic.getOriginalFilename());
return need;
}
result
Springboot project image upload and image path analysis (jar package form), please see another article ( ╹▽╹ )
https://blog.csdn.net/qq_42571665/article/details/121423941?spm=1001.2014.3001.5502 .