// 导入文件方法------------------------------------------------ // 创建文件 private void createFile(CommonsMultipartFile mediaFile, Coach coach) throws Exception { if (!mediaFile.isEmpty()) { String fileType = getFileType(mediaFile.getOriginalFilename()); String shortPath = "/static/upload/courseBg/"; String fileName = new Date().getTime() + fileType; String path = fileUtil.createMultiFolders(shortPath) + fileName; // 获取本地存储路径 coach.setUrl(shortPath + fileName); File file = new File(path); // 新建一个文件 mediaFile.getFileItem().write(file); // 将上传的文件写入新建的文件中 } }
/** * @param file * @param type * @return if return is "", there is a problem. */ public String upload(CommonsMultipartFile file, String type) { String filePath; String fileName; try { String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); fileName = type + "_" + System.currentTimeMillis() + suffix; filePath = this.baseDir + File.separator + fileName; File save = new File(filePath); file.getFileItem().write(save); } catch (Exception e) { e.printStackTrace(); return ""; } return this.path + fileName; }
@RequestMapping("/testFileUpload") public String handleUploadData( String name, @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) { if (!file.isEmpty()) { String path = this.servletContext.getRealPath("/upload/"); // 获取本地存储路径 System.out.println(path); String fileName = file.getOriginalFilename(); String fileType = fileName.substring(fileName.lastIndexOf(".")); System.out.println(fileType); File file2 = new File(path, new Date().getTime() + fileType); // 新建一个文件 try { file.getFileItem().write(file2); // 将上传的文件写入新建的文件中 } catch (Exception e) { e.printStackTrace(); } return "redirect:/meifaProduct"; } else { return "redirect:upload_error.jsp"; } }
@RequestMapping("uploadFile.do") public @ResponseBody Object uploadObject( @RequestParam("source") CommonsMultipartFile mFile, @ModelAttribute UploadSource uploadSource) { // System.out.println(mFile); try { // Set the expired time to one hour later. uploadSource.setInputStream(mFile.getInputStream()); ObjectMetadata objectMetaData = new ObjectMetadata(); objectMetaData.setContentType(mFile.getContentType()); objectMetaData.setContentLength(mFile.getFileItem().getSize()); uploadSource.setObjectMetaData(objectMetaData); ossService.uploadObject(uploadSource); // Thread.sleep(2000); return genSuccessResponse("", null); } catch (Exception e) { e.printStackTrace(); return genFailureResponse(e.getMessage()); } }