spring MultipartFile 转 File
一、方法一:
File.createTempFile(String prefix, String suffix);
创建一个临时File对象,或者new File()
MultipartFile.transferTo(File dest);
实现 MultipartFile to File
@RequestMapping("/uploadDutyExcelNew") @ResponseBody public String uploadDutyExcel(HttpServletRequest request, @RequestParam("file") MultipartFile multfile) throws Exception { // 获取文件名 String fileName = multfile.getOriginalFilename(); // 获取文件后缀 String prefix=fileName.substring(fileName.lastIndexOf(".")); // 用uuid作为文件名,防止生成的临时文件重复 final File excelFile = File.createTempFile(UUIDGenerator.getUUID(), prefix); // MultipartFile to File multfile.transferTo(excelFile); //你的业务逻辑 //程序结束时,删除临时文件 deleteFile(excelFile); return ""; } /** * 删除 * * @param files */ private void deleteFile(File... files) { for (File file : files) { if (file.exists()) { file.delete(); } } }
二、方法二:
引入commons-fileupload-1.2.2.jar
import org.apache.commons.fileupload.disk.DiskFileItem; CommonsMultipartFile cf = (CommonsMultipartFile)multfile; DiskFileItem fi = (DiskFileItem)cf.getFileItem(); File file = fi.getStoreLocation();