SpringBoot/SpringMvc实现文件上传功能
int index = originalFilename.lastIndexOf(".");用这个来获取".“的下标,然后再用subString进行截取”."以及之后的内容(也就是文件的后缀),然后再用UUID或者系统时间进行拼接文件后缀.
package com.pzx.admin.controller;
import lombok.extern.slf4j.Slf4j;
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.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* Created with IntelliJ IDEA.
* @Author: pzx
* @Date: 2021/09/15 20:34
* @Version:1.0
*
* 文件上传测试
*
*/
@Controller
@Slf4j
public class FormTestController {
@GetMapping("/form_layouts")
public String form_layouts() {
return "form/form_layouts";
}
/**
* 处理文件上传的请求
* MultipartFile 自动封装上传来的文件
* @param username
* @param email
* @param headerImg
* @param photos
* @return
*/
@PostMapping("/upload")
public String upload(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestPart("headerImg") MultipartFile headerImg,
//多文件上传
@RequestPart("photos") MultipartFile[] photos) throws IOException {
//1.@RequestPart这个注解用在multipart/form-data表单提交请求的方法上。
log.info("上传的信息:email={},username={},headerImg={},photos={}",
email, username, headerImg.getSize(), photos.length);
//先判断上传的文件是否为空
if (!headerImg.isEmpty()) {
//保存到文件服务器,一般阿里云的对象存储服务器OOS
String originalFilename = headerImg.getOriginalFilename();
//但是一般都是重写文件名,一般用uuid或者时间戳
// headerImg.transferTo(new File("D:\\44\\cache\\" + originalFilename));
//取得最后一个.的下标
int index = originalFilename.lastIndexOf(".");
String substring = originalFilename.substring(index);
File file = new File("D:\\44\\cache\\" + UUID.randomUUID().toString()+substring);
headerImg.transferTo(file);
}
if (photos.length > 0) {
for (MultipartFile photo : photos) {
if (!photo.isEmpty()) {
//但是一般都是重写文件名,一般用uuid或者时间戳
String originalFilename = photo.getOriginalFilename();
//取得最后一个.的下标
int index = originalFilename.lastIndexOf(".");
String substring = originalFilename.substring(index);
File file = new File("D:\\44\\cache\\" + UUID.randomUUID().toString()+substring);
photo.transferTo(file);
}
}
}
return "main";
}
}