1. 程式人生 > >SpringMVC實現FTP伺服器之圖片和富文字上傳

SpringMVC實現FTP伺服器之圖片和富文字上傳

上傳流程為:

jsp(上傳檔案)->springMVC的servlet.xml(解析成二進位制Mulitfile)->Controller->service(連線ftp,檔案打包按格式二進位制流上傳)->ftp

注:本文的程式碼是我mvc結構的程式碼,包括:jsp,Controller,service實現類,及工具類,property配置檔案,沒有寫出介面和Controller內的介面物件的注入,望周知!!!

一、圖片上傳

jsp:

<%--enctype(編碼方式)必須要宣告 name對應controller裡的檔案引數註解裡的value
--%> <%-- @RequestParam(value = "upload_file",required = false) MultipartFile file--%> <form name="form1" action="/manage/product/upload.do" enctype="multipart/form-data" method="post"> <input type="file" name="upload_file"> <button type="submit">SpringMVC上傳檔案</button> <%-- <input type
=
"submit" value="SpringMVC上傳檔案">--%> </form>

springMVC-servlet.xml:

<!-- 檔案上傳 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"/> <!--檔案上傳最大size 10m -->
<property name="maxInMemorySize" value="4096" /> <!--在記憶體中最大的size,上傳檔案時會使用記憶體--> <property name="defaultEncoding" value="UTF-8"></property> </bean>

Controller:

//SpringMVC,圖片檔案上傳,MultipartFile為SpringMVC封裝的方法
    @RequestMapping("upload.do")
    @ResponseBody  //序列化成json用
    public String upload( @RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request){
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file,path);
        return targetFileName;
    }

Service實現類

@Service(value = "iFileService")
public class FileServiceimpl implements IFileService {
    public String upload(MultipartFile file,String path){
        String fileName = file.getOriginalFilename(); //拿到上傳檔案的原始檔名
        //獲取副檔名,從檔名的最後一個.獲取.之後的字串即副檔名
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
        //為了防止不同使用者上傳的檔名重複,所以用UUID.副檔名
        String uploadFileName = UUID.randomUUID().toString()+"."+fileExtensionName;

        File fileDir = new File(path);
        if (!fileDir.exists()){ //如果這個檔案不存在,就建立
            fileDir.setWritable(true); //付許可權,讓這個檔案可寫
            //fileDir.mkdir();  上傳檔案時,如果目錄就一級時可以用
            fileDir.mkdirs();
        }
        File targetFile = new File(path,uploadFileName);

        try {
            file.transferTo(targetFile);
            //到這為止檔案已經上傳成功
            //todo 將targetfile上傳到ftp伺服器
            //用guava將檔案目標檔案上傳
            FTPUtil.uploadFile(Lists.newArrayList(targetFile));
            //執行完上面表示已經上傳到FTP伺服器上了
            //todo 上傳之後,刪除剛建立好的upload下面的檔案
            targetFile.delete();
        } catch (IOException e) {
            logger.error("上傳檔案異常",e);
        }

        return targetFile.getName();
    }
}

工具類

public class FTPUtil {
    private static String ftpIp = "127.0.0.1";
    private static String ftpUser = "ninka";
    private static String ftpPass = "ninka";

    private FTPClient ftpClient; //建立一個ftp客戶端物件
    public FTPClient getFtpClient() {
        return ftpClient;
    }
    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }
    //把具體邏輯封裝到private方法,remotePath表示要上傳到的資料夾w
    public boolean uploadFile(List<File> fileList) throws IOException {
        String remotePath = "img";
        boolean uploaded = true;
        FileInputStream fis = null;
        //連線FTP伺服器
        if (connectServer(ftpIp,21,ftpUser,ftpPass)){
            System.out.println("開始連線ftp伺服器");
            try {
                //設定需不需要切換資料夾
                ftpClient.changeWorkingDirectory(remotePath);
                //設定緩衝區
                ftpClient.setBufferSize(1024);
                //設定ftp字符集
                ftpClient.setControlEncoding("UTF-8");
                //把檔案型別設定成二進位制檔案型別,防止一些亂碼的問題
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                //開啟本地被動模式
                ftpClient.enterLocalPassiveMode();
                //遍歷檔案集合,把檔案放入儲存
                for (File fileItem : fileList){
                    fis = new FileInputStream(fileItem);
                    ftpClient.storeFile(fileItem.getName(),fis);
                }
            } catch (IOException e) {
                logger.error("上傳檔案異常",e);
                //如果檔案上傳異常了,那麼就把uploaded置成false
                uploaded = false;
            }finally {
                //關閉流
                fis.close();
                //關閉連線,防止開啟時間長了,出現異常
                ftpClient.disconnect();
            }
        }
        System.out.println("開始連線ftp伺服器,結束上傳,上傳結束:{}");
        return uploaded;
    }
    //連線FTP伺服器
    private boolean connectServer(String ip,int port,String user,String pwd){
        FTPClient ftpClient = new FTPClient();
        boolean isSuccess = false;
        try {
            ftpClient.connect(ip);
            isSuccess = ftpClient.login(user,pwd);
            System.out.println("連線伺服器成功");
            this.setFtpClient(ftpClient);
        } catch (IOException e) {
            logger.error("連線伺服器異常",e);
        }
        return isSuccess;
    }
}

二、富文字上傳
Controller

//富文字中對於返回值有自己的要求,我們使用的simditor所以按照simditor的要求來返回
        /*{
            "success": true/false,
                "msg": "error message", # optional
            "file_path": "[real file path]"
        }*/
//SpringMVC,富文字圖片檔案上傳
    @RequestMapping("richtext_image_upload.do")
    @ResponseBody
    public Map richtextImageUpload(HttpSession session
            , @RequestParam(value = "upload_file",required = false) MultipartFile file
            , HttpServletRequest request
            , HttpServletResponse response){
     String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file,path);
            if (StringUtils.isBlank(targetFileName)){
                map.put("success",false);
                map.put("msg","上傳失敗");
                return map;
            }
            //拼接和前端約定的url
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix");
            map.put("success",true);
            map.put("msg","上傳富文字檔案成功");
            map.put("file_path",url);
            //修改下response頭,前端有些外掛要求對後端返回的 有要求
            response.addHeader("Access-Controll-Allow-Headers","X-File-Name");
            return map;  
 }