JAVA实现FTP服务器上文件上传下载以及文件在线预览

(一)介绍文件上传下载:

(1)前端思路:

         用formData封装好file以及相关参数,然后l利用ajax请求往后台传数据
         

 html的代码:
    <input id="cm_file" type="file" name="upFileName">

 js代码: 
     var formData = new FormData();
     var cm_uploadFile = $('#cm_file',cmwes_page).get(0).files[0];//获取文件,这里cmwes_page可以不要,这是用来规定范围的

     formData.append("file",cm_uploadFile);
      $.ajax({
                url: '${rc.getContextPath()}/manage/cmWesData/saveCmWesData',
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false
            }).done(function(res) {
                
            }).fail(function(res) {

            });
  

(2)后台controller接受这个file类型的数据,然后传到service层进行处理

    //这里的file就是我前端封装到formdata中的参数‘file’
    @RequestMapping("saveCmWesData")
    @ResponseBody
    public HashMap<String,Object> saveCmWesData(@RequestParam("file") MultipartFile file,             
        HttpServletRequest request) throws IOException {
 cmWesDataService.upFileToFtp(file,fileName,fileSize,username,material,materialtext,stcode, stcodeDesc,fileDesc,fileNameTwo,version);
       //然后在service层进行上传、下载、删除的操作
           
    }

(3)上传、下载、删除的操作

    在上传的时候需要注意的是,把文件上传到ftp服务器的同时,也要把文件名,文件大小,文件类型保存到数据库中。

   先定义一些全局变量

  

 @Value("${uploadftp.path}")
    private  String basePath ;

    @Value("${uploadftp.servername}")
    private  String host ;

    @Value("${uploadftp.port}")
    private  int port ;

    @Value("${uploadftp.username}")
    private  String userName  ;

    @Value("${uploadftp.password}")
    private  String password ;

上传:

 @Transactional
    @Override
    public HashMap<String,Object> upFileToFtp(MultipartFile file, String fileName, String fileSize, String username, String material, String materialtext, String stcode,String stcodeDesc, String fileDesc,  String fileNameTwo,Integer version) throws IOException {
        HashMap<String,Object> hashMap = new HashMap<>();
        //String trueFileName = fileNameTwo.substring(0,fileName.indexOf("."))+".pdf";
        cmWesDataDao.insertWesData(fileNameTwo,fileSize,material,materialtext,stcode,stcodeDesc,fileDesc,username,version);
        FTPClient ftp = new FTPClient();
            fileName = new String(fileName.getBytes("GBK"),"iso-8859-1");// 转换后的目录名或文件名,解决中文乱码的问题
            FileInputStream input = (FileInputStream) file.getInputStream();
            int reply;
            ftp.connect(host,port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(userName, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                //return result;
            }
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath + filePath)) {
                //如果目录不存在创建目录
                if (!cn.evun.ime.platform.core.utils.StringUtils.isEmpty(filePath)) {
                    String[] dirs = filePath.split("/");
                    String tempPath = basePath;
                    for (String dir : dirs) {
                        if (null == dir || "".equals(dir)) continue;
                        tempPath += "/" + dir;
                        logger.info("地址=============================="+tempPath);
                        if (!ftp.changeWorkingDirectory(tempPath)) {
                            if (!ftp.makeDirectory(tempPath)) {
                                //return result;
                            } else {
                                ftp.changeWorkingDirectory(tempPath);
                            }
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            if (!ftp.storeFile(fileName, input)) {
               /* CmWesDataServiceImpl cmWesDataService = new CmWesDataServiceImpl();
                cmWesDataService.convert2PDF(basePath+filePath+fileName,basePath+filePath+trueFileName);
                delCmWesData(fileName);
                logger.info("==================================删除成功==========================");*/
            }
            input.close();
            ftp.logout();
            hashMap.put("ftpFlag","true");
            return hashMap;
            //ftp上传之后,把相关信息保存到数据库中去
            //cmWesDataService.selectWesDateVer(fileName);

    }

 下载:主要是返回一个路径,然后前端直接调用一个前端方法就能实现浏览器下载

 @Override
    public String getDownCmWesDataUrl(String filename) throws UnsupportedEncodingException {
        return "ftp://"+host+filePath+URLEncoder.encode(filename, "GBK");
    }




然后前端接受到这个url,直接window.location.href = url,就能实现浏览器下载了

删除:根据文件名,先去保存文件相关信息的表中删除,然后再去ftp服务器上删除相关信息

    @Override
    @Transactional
    public HashMap<String, Object> delCmWesData(String filename) throws IOException {
        HashMap<String,Object> hashMap = new HashMap<>();
        String filenameTwo = filename;
        filename = new String(filename.getBytes("GBK"),"iso-8859-1");
        cmWesDataDao.delCmWesData(filenameTwo);//先去数据库中删除数据
        String path = basePath+filePath;
        FTPClient ftp = new FTPClient();
        ftp.connect(host);
        ftp.login(userName,password);
        ftp.changeWorkingDirectory(path);//切换工作目录
        ftp.dele(filename);
        ftp.logout();
        hashMap.put("delFlag","true");
        return hashMap;
    }

(二)实现文件的在线预览功能,其实就是要把word、ppt、excel等格式的文档转化为pdf,然后前端也是调用            window.location.href = url这个方法,就能实现pdf预览功能。

   (1)其中做预览的过程中遇到了几个小问题。如何转化word、ppt、excel成pdf,然后一般开发都是用windows系统,但是部署项目一般都是linux服务器,所以调试的时候会有点麻烦。其中我这边参考有价值的文档,到时候我会放在末尾供大家参考。

我转pdf用的是openoffice工具,然后你需要在linux上安装这个openoffice工具,但是在测试的时候会发现word中的中文字体都乱掉了,所以需要添加windows的字体到linux系统上,这边我也是参考网上资料,到时候添出链接给大家。我是先写demo,然后demo测试通过之后,再在业务代码中需要用到的地方替换进去就好了。demo逻辑:先在maven中引入依赖,然后再进行操作。

 <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>


        <dependency>
            <groupId>com.github.livesense</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>1.0.5</version>
        </dependency>
package cn.evun.ime.mm.controller;

import java.io.File;
import java.io.FileNotFoundException;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

/**
 * <strong>Title :<br></strong>
 * <strong>Package : <br></strong>
 * <strong>Description : </strong><br>
 * <strong>Create on : 2018/10/12<br></strong>
 * <p>
 *
 * @author tengwei.wang<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class OpenOfficePdfConvert {
    /**
     * @param args
     */
    private static OfficeManager officeManager;
    //private static String OFFICE_HOME = "C:/Program Files (x86)/OpenOffice 4/";
    private static String OFFICE_HOME = "/opt/openoffice4/";
    private static int port[] = { 8100 };

    public void convert2PDF(String inputFile, String outputFile) throws FileNotFoundException {

        startService();
        System.out.println("进行文档转换转换:" + inputFile + " --> " + outputFile);

        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        converter.convert(new File(inputFile), new File(outputFile));

        stopService();
        System.out.println();

    }

    // 打开服务器
    public static void startService() {
        DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
        try {
            System.out.println("准备启动服务....");
            configuration.setOfficeHome(OFFICE_HOME);// 设置OpenOffice.org安装目录
            configuration.setPortNumbers(port); // 设置转换端口,默认为8100
            configuration.setTaskExecutionTimeout(1000 * 60 * 5L);// 设置任务执行超时为5分钟
            configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);// 设置任务队列超时为24小时

            officeManager = configuration.buildOfficeManager();
            officeManager.start(); // 启动服务
            System.out.println("office转换服务启动成功!");
        } catch (Exception ce) {
            System.out.println("office转换服务启动失败!详细信息:" + ce);
        }
    }

    // 关闭服务器
    public static void stopService() {
        System.out.println("关闭office转换服务....");
        if (officeManager != null) {
            officeManager.stop();
        }
        System.out.println("关闭office转换成功!");
    }

    public static void main(String[] args) throws Exception {
        String path = "/usr/ftp/test";
        OpenOfficePdfConvert opc = new OpenOfficePdfConvert();
        //opc.convert2PDF(path+"a.docx", path+"a.pdf");
        opc.convert2PDF(path+"a.docx", path+"c.pdf");
        //opc.convert2PDF(path+"a.pptx", path+"c.pdf");
    }
}

https://blog.csdn.net/u013132051/article/details/53514696

https://blog.csdn.net/zsg88/article/details/77788345

  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值