電商專案之springmvc實現檔案上傳到FTP伺服器(超級重點)
阿新 • • 發佈:2019-01-11
1、前端(name的值和介面的@RequestParam的value相同,並且enctype為multipart/form-data)
springmvc檔案上傳到ftp伺服器 <form name="form1" action="/manage/product/upload.do" method="post" enctype="multipart/form-data"> <input type="file" name="upload_file"/> <input type="submit" value="springmvc上傳檔案"/> </form>
2、後端介面(controller)
/** * 檔案上傳到ftp伺服器上(在springmvc上配置了檔案上傳的配置) * @param file * @param request * @return */ @RequestMapping("upload.do") @ResponseBody public ServerResponse upload(HttpSession session,@RequestParam(value="upload_file",required = false)MultipartFile file, HttpServletRequest request){ User user= (User) session.getAttribute(Const.CURRENT_USER); if(user==null){ return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"使用者未登陸,請登陸管理員"); } if(iUserService.checkAdminRole(user).isSuccess()){//表示是管理員 //業務邏輯 //從request裡面拿 String path=request.getSession().getServletContext().getRealPath("upload"); String targetFileName=iFileService.upload(file,path); String url= PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName; Map fileMap= Maps.newHashMap(); fileMap.put("uri",targetFileName); fileMap.put("url",url); return ServerResponse.createBySuccess(fileMap); }else { return ServerResponse.createByErrorMessage("無許可權操作"); } }
3、serviceImpl
package com.lpy.mall.service.Impl; import com.google.common.collect.Lists; import com.lpy.mall.service.IFileService; import com.lpy.mall.util.FTPUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID; @Service("iFileService") public class FileServiceImpl implements IFileService { private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class); /** * @param file * @param path 為上傳的一個路徑 * @return */ public String upload(MultipartFile file,String path){ //1、拿到我們上傳檔案的檔名 String fileName=file.getOriginalFilename(); //2、獲取副檔名 abc.jpg abc.abc.abc.jpg 拿取最後一個. String fileExtensionName=fileName.substring(fileName.lastIndexOf(".")+1); //3、上傳後的檔案的檔名 String uploadFileName= UUID.randomUUID().toString()+"."+fileExtensionName; logger.info("開始上傳檔案,上傳檔案的檔名:{},上傳的路徑:{},新檔名:{}",fileName,path,uploadFileName); //4、宣告目錄的file File fileDir = new File(path); if(!fileDir.exists()){ fileDir.setWritable(true);//使這檔案有寫的許可權 fileDir.mkdirs();//建立目錄 } //5、宣告我們的檔案 (路徑加我們的新的檔名) File targetFile = new File(path,uploadFileName); try { file.transferTo(targetFile); //到這裡,檔案已經上傳成功 //將targetFile上傳到問們的FTP伺服器上 FTPUtil.uploadFile(Lists.<File>newArrayList(targetFile)); //已經上傳到ftp伺服器上 //上傳完之後,刪除upload下面的檔案 targetFile.delete(); } catch (IOException e) { logger.error("檔案上傳異常",e); return null; } return targetFile.getName(); } }