import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/files")
public class FileUploadController {
// 单文件上传
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "请选择要上传的文件");
return "redirect:uploadStatus";
}
// 处理上传的文件,例如保存到服务器
try {
byte[] bytes = file.getBytes();
// 这里可以写代码将文件内容保存到服务器
// ...
redirectAttributes.addFlashAttribute("message", "文件上传成功");
return "redirect:uploadStatus";
} catch (Exception e) {
e.printStackTrace();
}
redirectAttributes.addFlashAttribute("message", "文件上传失败");
return "redirect:uploadStatus";
}
// 多文件上传
@PostMapping("/uploadMultiple")
public String handleMultipleFileUpload(@RequestParam("files") MultipartFile[] files,
RedirectAttributes redirectAttributes) {
if (files.length == 0) {
redirectAttributes.addFlashAttribute("message", "请选择要上传的文件");
return "redirect:uploadStatus";
}
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue; // 跳过空文件
}
try {
byte[] bytes = file.getBytes();
// 这里可以写代码将文件内容保存到服务器
// ...
} catch (Exception e) {
e.printStackTrace();
}
}
redirectAttributes.addFlashAttribute("message", "所有文件上传成功");
return "redirect:uploadStatus";
}
// 显示上传结果
@RequestMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
}
评论已关闭