Java 多文件上传(transferTo)
1.在application.properties中配置文件路径
file.upload.url:E:/test/upload/file
2.文件上传代码
import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.util.ObjectUtils; 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.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.*; @RestController @RequestMapping("file") public class UploadController { @ApiOperation(value="多文件上传") @PostMapping( value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public Object upload(@RequestParam("file") MultipartFile[] file){ Map<String,Object> map = new HashMap<>(); map.put("status",200); List<Map<String,Object>> result = new ArrayList<>(); if(!ObjectUtils.isEmpty(file) && file.length>0){ Arrays.asList(file).stream().forEach(files->result.add(singleFileUpload(files))); } map.put("data",result); return map; } //获取配置路径 @Value("${file.upload.url}") private String uploadFilePath; private Map<String, Object> singleFileUpload(MultipartFile files) { Map<String,Object> map = new HashMap<>(); //防止因文件名重复导致文件丢失 String path = new String(uploadFilePath+"_"+UUID.randomUUID().toString().replace("-","").toLowerCase()); //文件路径 File dest =new File(path+File.separator+ files.getOriginalFilename()); if(!dest.getParentFile().exists()){ //避免文件创建失败,如果文件夹不存在,则创建 dest.getParentFile().mkdirs(); } try { files.transferTo(dest); map.put("url",dest); map.put("fileName",files.getOriginalFilename()); map.put("success",1); map.put("result","文件上传成功"); } catch (IOException e) { e.printStackTrace(); map.put("success",2); map.put("result","文件上传失败"); } return map; //返回文件名乱码问题 //HttpHeaders headers = new HttpHeaders(); //MediaType mediaType = new MediaType("text","html", Charset.forName("utf-8")); //headers.setContentType(mediaType); //return new ResponseEntity<String>(js,headers, HttpStatus.OK); } }
3.postman测试

4.文件保存地址
final:不积跬步,无以至千里.不积小流,无以成江海
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~