java上传图片到ftp

 最近在弄新闻编辑后台的管理程序,由于公司没有图片服务器,后台的程序和前台的程序分离。前台和后台都是部署在集群上。要想共享上传的图片,我们在每台机器上开了个ftp。在提交的时候同时将文件上传到ftp上。

 

页面展示选择了kindEdit   js框架。

 

上传本地图片到服务器的程序如下:

 

<%@ page pageEncoding="gbk"%>
<%@page
 import="java.util.*,java.io.*,  
    org.apache.commons.fileupload.FileItem,  
    org.apache.commons.fileupload.FileUploadException,  
    org.apache.commons.fileupload.disk.DiskFileItemFactory,  
    org.apache.commons.fileupload.servlet.ServletFileUpload,  
    java.util.concurrent.locks.*,
    com.glot.csp.lottery.common.ftp.*"%>
<%  
    String id = "";  
    String url = "";  
    String imgTitle = "";  
    String imgWidth = "";  
    String imgHeight = "";  
    String imgBorder = "";  
    String filePath = "";  
    String align = "";  
    // **************************************  
    // 初始化上传工厂对象  
    DiskFileItemFactory factory = new DiskFileItemFactory();  
    // 设置上传工厂对象限制  
    factory.setSizeThreshold(1024 * 1024 * 20);  
    factory.setRepository(new File(request.getSession(true)  
            .getServletContext().getRealPath("/")));  
    // 创建上传对象  
    ServletFileUpload upload = new ServletFileUpload(factory);  
    upload.setFileSizeMax(1024 * 1024 * 20);  
    List items = null;
    System.out.println("*************MMMM&&&&&&&&&"); 
    try {  
        items = upload.parseRequest(request);  
    } catch (FileUploadException e) {  
        e.printStackTrace(System.out);  
    }  
    for (Iterator i = items.iterator(); i.hasNext();) {  
        FileItem item = (FileItem)i.next();  
        if (item.isFormField()) {  
            String name = item.getFieldName();  
            String value = item.getString("gbk");  
            if (name.equals("id")) {  
                id = value;  
            } else if (name.equals("imgTitle")) {  
                imgTitle = value;  
            } else if (name.equals("imgWidth")) {  
                imgWidth = value;  
            } else if (name.equals("imgHeight")) {  
                imgHeight = value;  
            } else if (name.equals("imgBorder")) {  
                imgBorder = value;  
            } else if (name.equals("align")) {  
                align = value;  
            } else if (name.equals("url")) {  
                filePath = value;  
            }  
        } else {  
            // 取得表单域名  
            String fieldName = item.getFieldName();  
            // 取得文件名  
            String fileName = item.getName();  
            // 取得文件类型  
            String contentType = item.getContentType();  
              
            final Lock lock = new ReentrantLock();  
            String newName = null;  
            lock.lock();  
            try {  
                //加锁为防止同一时间文件名冲突   
                newName = System.currentTimeMillis()  
                        + fileName.substring(fileName.lastIndexOf("."),  
                                fileName.length());  
            } catch (Exception e) {  
                e.printStackTrace(System.err);  
            } finally {  
                lock.unlock();  
            }  
            filePath = "./ke_upload/" + newName;  
            File file = new File(request.getSession()
   .getServletContext().getRealPath("/")
   + "//ke_upload");
   if (!file.exists()) {
  file.mkdirs();
  }
  String path = request  
                    .getSession().getServletContext().getRealPath("/")  
                    + "//ke_upload//" + newName;
            FileOutputStream fos = new FileOutputStream(path);  
            if (item.isInMemory()) {  
                fos.write(item.get());  
                fos.close();  
            } else {  
                InputStream in = item.getInputStream();  
                byte[] buffer = new byte[1024];  
                int len;  
                while ((len = in.read(buffer)) > 0) {  
                    fos.write(buffer, 0, len);  
                }  
                in.close();  
                fos.close();
               
            }
            new TransferFileFtp().copyFileToFtp(path);   
        }  
    }  
    out.println("<html><head><title>Insert Image</title><meta http-equiv='content-type' content='text/html; charset=gbk'/></head><body>");  
    out.println("<script type='text/javascript'>");  
    out.println("parent.parent.KE.plugin['image'].insert('" + id  
            + "','" + filePath + "','" + imgTitle + "','" + imgWidth  
            + "','" + imgHeight + "','" + imgBorder + "','" + align  
            + "');</script>");  
    out.println("</body></html>");  
%>

 

由服务器上传图片到ftp的代码如下:

 

package com.glot.csp.lottery.common.ftp;

import java.io.FileInputStream;
import java.io.IOException;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

public class TransferFileFtp {
 static FtpClient ftpClient;

 private Configuration configura = Configuration.getInstance();

 /**
  * 连接FTP、复制文件
  *
  * @throws Exception
  */
 public boolean copyFileToFtp(String path) throws Exception {

  try {
   ftpConnect();

   if (!isExistDir(configura.getValue("ftpFilePath")))
    mkDir(configura.getValue("ftpFilePath"));

   String[] sFileName;

   System.out.println(ftpClient.pwd());

   sFileName = path.split(configura.getValue("splitString"));

   TelnetOutputStream ftpOut = ftpClient
     .put(sFileName[sFileName.length - 1]);

   FileInputStream fs = new FileInputStream(path);
   TelnetInputStream ftpIn = new TelnetInputStream(fs, true);
   byte[] buf = new byte[204800];
   int bufsize = 0;
   while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
    ftpOut.write(buf, 0, bufsize);
   }

   ftpIn.close();
   ftpOut.close();

   System.out.println(ftpClient.getResponseString());

  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }
  ftpClient.sendServer("QUIT/r/n");
  return true;
 }

 /**
  * 连接FTP
  *
  */
 private void ftpConnect() {
  try {
   ftpClient = new FtpClient(configura.getValue("ipAdress"), Integer
     .parseInt(configura.getValue("port")));
   ftpClient.login(configura.getValue("userName"), configura
     .getValue("passWord"));
   ftpClient.binary();//避免传递的图片失真
   System.out.println(ftpClient.welcomeMsg);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 /**
  * 判断ftp上是否存在路径
  *
  * @return boolean
  */
 private boolean isExistDir(String path) {
  try {
   ftpClient.cd(path);
  } catch (IOException e) {
   return false;
  }
  return true;
 }

 /**
  * 在ftp上创建文件夹
  *
  * @param dir
  *            文件夹名字
  */
 private void mkDir(String dir) {

  ftpClient.sendServer("MKD " + dir + "/r/n");

 }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值