日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

springboot上傳文件到Nginx代理的FTP文件服務器

作者:低調波 更新時間: 2022-04-11 編程語言

上傳文件

Controller層:

    //圖片類型校驗
    @Value("${picture.pictureType}")
    private String pictureType;// pictureType: ^.+.(jpg|png|gif|webp)$
    //圖片大小校驗
    @Value("${file.limitSize}")
    private String pictureSize; 
/**
     * @author bobo
     * 上傳圖片信息
     */
    @PostMapping("/insertTreeImage")
    public AjaxResult insertTreeImage(@RequestBody MultipartFile file, @RequestParam("id") Long id) throws IOException {
        //限制圖片大小
        String regex=pictureSize.replaceAll("[A-Z]{2}","");
        Long limit=(Long.parseLong(regex))*1024;
        Long size = file.getSize()/1024;
        //限制圖片類型
        if(!file.getOriginalFilename().matches(pictureType)){
            throw new BizException(BizCodeEnum.FILE_UPLOAD_TYPE_FAIL);
        } else if (file.isEmpty() || file==null){//驗證圖片是否為空
            throw new BizException(BizCodeEnum.FILE_UPLOAD_NOTFOUND_FAIL);
        }else if(size>=limit){//限制圖片大小
            throw new BizException(BizCodeEnum.FILE_UPLOAD_SIZE_FAIL);
        }else {
            AjaxResult ajaxResult = ancientTreeService.uploadTreeImage(file, id);

            return AjaxResult.success("操作成功",ajaxResult);
        }
    }

service層:

 AjaxResult uploadTreeImage(MultipartFile file, Long id) throws IOException;

impl:

  /**
     * 上傳圖片的方法
     * @param file
     * @param id
     * @author bobo
     */
    @Override
    public AjaxResult uploadTreeImage(@RequestBody MultipartFile file , Long id) throws IOException {
        //獲得圖片原來的名稱
        String fileName=file.getOriginalFilename();
        //防止上傳后重名問題創建一個md5隨機名稱的文件夾
        String uploadFileName= UUID.randomUUID().toString();
        //按時間存放
        String strNow = new SimpleDateFormat("yyyyMMdd").format(new Date()).toString();
        String newFileName = uploadFileName;
        //對文件夾名稱進行拼接作為上傳路徑
        String filePath="/"+ LitchiDirectoryName.AncientTreeDirName +"/"+strNow+"/"+newFileName;
        //拼接地址作為上傳路徑
        String url=nginxUrl+filePath+"/"+fileName;
        //數據存入數據庫
        String address =filePath+"/"+fileName;
        AncientTreeDO ancientTreeDO=new AncientTreeDO().setTreeImage(address).setId(id);
        ancientTreeMapper.updateAncientTreePath(ancientTreeDO);

        try {
            //拿到輸入流后傳入ftp
            InputStream input=null;
            input = file.getInputStream();
            /** 連接ftp進行上傳
              * ftpIp:自定義的ftpip地址
              * port: 端口 (默認21)
              * ftpUser: ftp用戶名
              * ftpPass:ftp密碼
              * basePath:上傳后的根目錄
              * filePath:上傳文件的文件路徑
              * fileName:上傳后的文件名
              * input:輸入流數據
              * **/
            boolean b = FtpUtil.uploadFile(ftpIp, port, ftpUser, ftpPass, basePath, filePath, fileName, input);
            if(b){
                //返回url地址進行圖片反顯
                return AjaxResult.success(url);
            }else {
                AjaxResult.error(425,"MESSAGE ERROR");
            }
        } catch (IOException e) {
            log.error("文件上傳異常",e);

        }

        
        return AjaxResult.success(nginxUrl);
    }

FTP工具類:

public class FtpUtil {
    /**
     * Description: 向FTP服務器上傳文件
     *
     * @param host     FTP服務器ip
     * @param port     FTP服務器端口
     * @param username FTP登錄賬號
     * @param password FTP登錄密碼
     * @param basePath FTP服務器基礎目錄,/home/ftpuser/images
     * @param filePath FTP服務器文件存放路徑。例如分日期存放:/2018/05/28。文件的路徑為basePath+filePath
     * @param filename 上傳到FTP服務器上的文件名
     * @param input    輸入流
     * @return 成功返回true,否則返回false
     */
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);// 連接FTP服務器
            // 如果采用默認端口,可以使用ftp.connect(host)的方式直接連接FTP服務器
            ftp.login(username, password);// 登錄
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }

                //切換到上傳目錄
                if (!ftp.changeWorkingDirectory(basePath + filePath)) {                //如果目錄不存在創建目錄
                    String[] dirs = filePath.split("/");
                    String tempPath = basePath;
                    for (String dir : dirs) {
                        if (null == dir || "".equals(dir)) continue;
                        tempPath += "/" + dir;
                        if (!ftp.changeWorkingDirectory(tempPath)) {
                            if (!ftp.makeDirectory(tempPath)) {
                                return result;
                            } else {
                                ftp.changeWorkingDirectory(tempPath);
                            }
                        }
                    }
                }            //設置為被動模式
                ftp.setBufferSize(1024 * 1024 * 2);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(input);
                ftp.enterLocalPassiveMode();            //設置上傳文件的類型為二進制類型
                ftp.setFileType(FTP.BINARY_FILE_TYPE);            //上傳文件
                if (!ftp.storeFile(filename, bufferedInputStream)) {
                    return result;
                }
                input.close();
                ftp.logout();
                result = true;

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
}

以上就是FTP上傳的所有內容了,如果對你有幫助請點個贊

原文鏈接:https://blog.csdn.net/aaa58962458/article/details/121038457

欄目分類
最近更新