jsp下载ftp
A. jsp实现点击超链接下载文件
/** *//**
* 实现文件另存功能
*
* @param text
* 文件内容
* @param fileName
* 文件名称
* @return
*/
protected String renderFile(String text, String fileName)
throws IOException
{
response.addHeader("Content-Disposition", "attachment; filename="
+ fileName);
response.setContentType("application/octet-stream");
response.setCharacterEncoding("GB2312");
response.getWriter().write(text);
response.flushBuffer();
response.getWriter().close();
return null;
}
下载的action:
/** *//**
* 提供下载的方法
* @return
*/
public String down()
{
String dir = getFullPath() + "/upload/file/";
try
{
if (!FileUtils.exists(dir))
{
new File(dir).mkdirs();
}
Random r = new Random(System.currentTimeMillis());
Integer randomInt = r.nextInt();
this.renderFile("test content:" + randomInt,randomInt + ".txt");
}
catch (IOException e)
{
e.printStackTrace();
this.renderText(e.getMessage());
}
return null;
}
页面链接调用:
下载
B. jsp 如何实现文件上传和下载功能
上传:
MyjspForm mf = (MyjspForm) form;// TODO Auto-generated method stub
FormFile fname=mf.getFname();
byte [] fn = fname.getFileData();
OutputStream out = new FileOutputStream("D:\"+fname.getFileName());
Date date = new Date();
String title = fname.getFileName();
String url = "d:\"+fname.getFileName();
Upload ul = new Upload();
ul.setDate(date);
ul.setTitle(title);
ul.setUrl(url);
UploadDAO uld = new UploadDAO();
uld.save(ul);
out.write(fn);
out.close();
下载:
DownloadForm downloadForm = (DownloadForm)form;
String fname = request.getParameter("furl");
FileInputStream fi = new FileInputStream(fname);
byte[] bt = new byte[fi.available()];
fi.read(bt);
//设置文件是下载还是打开以及打开的方式msdownload表示下载;设置字湖集,//主要是解决文件中的中文信息
response.setContentType("application/msdownload;charset=gbk");
//文件下载后的默认保存名及打开方式
String contentDisposition = "attachment; filename=" + "java.txt";
response.setHeader("Content-Disposition",contentDisposition);
//设置下载长度
response.setContentLength(bt.length);
ServletOutputStream sos = response.getOutputStream();
sos.write(bt);
return null;
C. 公司要求做一个java和jsp怎么实现ftp上传的功能模块,我没有做过,谁有讲得细一点的文章或网站。
form表单提交文件,建议用smartupload上传,暂存在web服务器目录下,然后稍微一下下面的代码,ftp上传后,删除暂存文件,ok
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
/**
 * Ftp 服务类,对Apache的commons.net.ftp进行了包装<br>
 * 依赖库文件:commons-net-1.4.1.jar
 * 
 * @version 1.0 2008-02-18
 * @author huchao@jbsoft
 */
public class FtpService {
 public FtpService(String serverAddr, String lsenport, String userName,
   String pswd) {
  this.ftpServerAddress = serverAddr;
  this.port = Integer.parseInt(lsenport);
  this.user = userName;
  this.password = pswd;
 }
 /**
  * FTP 服务器地址
  */
 private String ftpServerAddress = null;
 /**
  * FTP 服务端口
  */
 private int port = 21;
 /**
  * FTP 用户名
  */
 private String user = null;
 /**
  * FTP 密码
  */
 private String password = null;
 /**
  * FTP 数据传输超时时间
  */
 private int timeout = 0;
 /**
  * 异常:登录失败
  */
 private final I2HFException EXCEPTION_LOGIN = new I2HFException("COR101",
   "FTP服务器登录失败");
 /**
  * 异常:文件传输失败
  */
 private final I2HFException EXCEPTION_FILE_TRANSFER = new I2HFException(
   "COR010", "FTP文件传输失败");
 /**
  * 异常:IO异常
  */
 private final I2HFException EXCEPTION_GENERAL = new I2HFException("COR010",
   "FTP IO 异常");
 private static final Logger logger = Logger.getLogger(FtpService.class);
 /**
  * 初始化FTP连接,并进行用户登录
  * 
  * @return FTPClient
  * @throws I2HFException
  */
 public FTPClient initConnection() throws I2HFException {
  FTPClient ftp = new FTPClient();
  try {
   // 连接到FTP
   ftp.connect(ftpServerAddress, port);
   int reply = ftp.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    throw new I2HFException("COR010", "FTP服务器连接失败");
   }
   // 登录
   if (!ftp.login(user, password)) {
    throw EXCEPTION_LOGIN;
   }
   // 传输模式使用passive
   ftp.enterLocalPassiveMode();
   // 设置数据传输超时时间
   ftp.setDataTimeout(timeout);
   logger.info("FTP服务器[" + ftpServerAddress + " : " + port + "]登录成功");
  } catch (I2HFException te) {
   logger.info(te.errorMessage, te);
   throw te;
  } catch (IOException ioe) {
   logger.info(ioe.getMessage(), ioe);
   throw EXCEPTION_LOGIN;
  }
  return ftp;
 }
 /**
  * 设置传输方式
  * 
  * @param ftp
  * @param binaryFile
  *            true:二进制/false:ASCII
  * @throws I2HFException
  */
 public void setTransferMode(FTPClient ftp, boolean binaryFile)
   throws I2HFException {
  try {
   if (binaryFile) {
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    logger.info("FTP文件传输方式为:二进制");
   } else {
    ftp.setFileType(FTP.ASCII_FILE_TYPE);
    logger.info("FTP文件传输方式为:ASCII");
   }
  } catch (IOException ex) {
   logger.info(ex.getMessage(), ex);
   throw EXCEPTION_GENERAL;
  }
 }
 /**
  * 在当前工作目录下建立多级目录结构
  * 
  * @param ftp
  * @param dir
  * @throws I2HFException
  */
 public void makeMultiDirectory(FTPClient ftp, String dir)
   throws I2HFException {
  try {
   StringBuffer fullDirectory = new StringBuffer();
   StringTokenizer toke = new StringTokenizer(dir, "/");
   while (toke.hasMoreElements()) {
    String currentDirectory = (String) toke.nextElement();
    fullDirectory.append(currentDirectory);
    ftp.makeDirectory(fullDirectory.toString());
    if (toke.hasMoreElements()) {
     fullDirectory.append('/');
    }
   }
  } catch (IOException ex) {
   logger.info(ex.getMessage(), ex);
   throw EXCEPTION_GENERAL;
  }
 }
 /**
  * 更改服务器当前路径
  * 
  * @param ftp
  * @param dir
  * @throws I2HFException
  */
 public void changeWorkingDirectory(FTPClient ftp, String dir)
   throws I2HFException {
  try {
   if (!ftp.changeWorkingDirectory(dir)) {
    throw new I2HFException("COR010", "目录[ " + dir + "]进入失败");
   }
  } catch (I2HFException tfe) {
   logger.info(tfe.errorMessage, tfe);
   throw tfe;
  } catch (IOException ioe) {
   logger.info(ioe.getMessage(), ioe);
   throw EXCEPTION_GENERAL;
  }
 }
 /**
  * 上传文件到FTP服务器
  * 
  * @param ftp
  * @param localFilePathName
  * @param remoteFilePathName
  * @throws I2HFException
  */
 public void uploadFile(FTPClient ftp, String localFilePathName,
   String remoteFilePathName) throws I2HFException {
  InputStream input = null;
  try {
   input = new FileInputStream(localFilePathName);
   boolean result = ftp.storeFile(remoteFilePathName, input);
   if (!result) {
    // 文件上传失败
    throw EXCEPTION_FILE_TRANSFER;
   }
   logger.info("文件成功上传到FTP服务器");
  } catch (I2HFException tfe) {
   logger.info(tfe.getMessage(), tfe);
   throw tfe;
  } catch (IOException ioe) {
   logger.info(ioe.getMessage(), ioe);
   throw EXCEPTION_FILE_TRANSFER;
  } finally {
   try {
    if (input != null) {
     input.close();
    }
   } catch (IOException ex) {
    logger.info("FTP对象关闭异常", ex);
   }
  }
 }
 /**
  * 下载文件到本地
  * 
  * @param ftp
  * @param remoteFilePathName
  * @param localFilePathName
  * @throws I2HFException
  */
 public void downloadFile(FTPClient ftp, String remoteFilePathName,
   String localFilePathName) throws I2HFException {
  boolean downloadResult = false;
  OutputStream output = null;
  try {
   output = new FileOutputStream(localFilePathName);
   downloadResult = ftp.retrieveFile(remoteFilePathName, output);
   if (!downloadResult) {
    // 如果是文件不存在将异常抛出
    throw new I2HFException("COR011", "文件不存在");
   }
   logger.info("文件成功从FTP服务器下载");
  } catch (I2HFException tfe) {
   logger.error(tfe.getMessage(), tfe);
   throw tfe;
  } catch (IOException ex) {
   logger.error(ex.getMessage(), ex);
   throw EXCEPTION_FILE_TRANSFER;
  } finally {
   try {
    if (output != null) {
     output.close();
    }
    if (!downloadResult) {
     new File(localFilePathName).delete();
    }
   } catch (IOException ex) {
    logger.error("FTP对象关闭异常", ex);
   }
  }
 }
 /**
  * Method setFtpServerAddress.
  * 
  * @param ftpServerAddress
  *            String
  */
 public void setFtpServerAddress(String ftpServerAddress) {
  this.ftpServerAddress = ftpServerAddress;
 }
 /**
  * Method setUser.
  * 
  * @param user
  *            String
  */
 public void setUser(String user) {
  this.user = user;
 }
 /**
  * Method setPassword.
  * 
  * @param password
  *            String
  */
 public void setPassword(String password) {
  this.password = password;
 }
 /**
  * Method setTimeout.
  * 
  * @param timeout
  *            String
  */
 public void setTimeout(String timeout) {
  try {
   this.timeout = Integer.parseInt(timeout);
  } catch (NumberFormatException ex) {
   // 默认超时时间500毫秒
   this.timeout = 500;
  }
 }
 /**
  * Method setPort.
  * 
  * @param port
  *            String
  */
 public void setPort(String port) {
  try {
   this.port = Integer.parseInt(port);
  } catch (NumberFormatException ex) {
   // 默认端口21
   this.port = 21;
  }
 }
} 
=====================================
jsp上传部分
===================================
<form method="post" name="uploadform" id="uploadform" action="upload" ENCTYPE="multipart/form-data">
       
       <input  type="hidden" name="service" value="com.jbsoft.i2hf.corpor.services.CstBatchBizServices.exclUpload"/>
       <table cellspacing="0" cellpadding="0">
        <tr>
         <td width="20%" align="right">上传本地文件:</td>
            <td width="80%"><input class="" style="width:300px" type="file" width="300px" name="exclname" id="exclname"/></td>
        </tr>
       </table>
      </form>
============================================
上传的servlet用的是smartupload
,部分代码可以参考一下:
==========================================
SmartUpload su = new SmartUpload();
   su.setCharset("UTF-8");
   su.initialize(getServletConfig(), request, response);
   su.setMaxFileSize(10240000);
   su.setTotalMaxFileSize(102400000);
   su.setAllowedFilesList("xls");
   su.upload();
===========================================
代码里面有一些客户的信息,不能全部给你哈
D. jsp 文件上传和下载
1.jsp页面 
<s:form action="fileAction" namespace="/file" method="POST" enctype="multipart/form-data"> 
    <!-- name为后台对应的参数名称 --> 
    <s:file name="files" label="file1"></s:file> 
    <s:file name="files" label="file2"></s:file> 
    <s:file name="files" label="file3"></s:file> 
    <s:submit value="提交" id="submitBut"></s:submit> 
</s:form>
2.Action 
//单个文件上传可以用 File files,String filesFileName,String filesContentType 
//名称要与jsp中的name相同(三个变量都要生成get,set) 
private File[] files; 
// 要以File[]变量名开头 
private String[] filesFileName; 
// 要以File[]变量名开头 
private String[] filesContentType; 
 
private ServletContext servletContext; 
 
//Action调用的上传文件方法 
public String execute() { 
      ServletContext servletContext = ServletActionContext.getServletContext(); 
      String dataDir = servletContext.getRealPath("/file/upload"); 
      System.out.println(dataDir); 
      for (int i = 0; i < files.length; i++) { 
            File saveFile = new File(dataDir, filesFileName[i]); 
            files[i].renameTo(saveFile); 
      } 
      return "success"; 
}
3.配置上传文件临时文件夹(在struts.xml中配置) 
<constant name="struts.multipart.saveDir" value="c:/temp"/>
文件下载
1.下载的url(到Action) 
<a href="${pageContext.request.contextPath}/file/fileAction!down.action">下载</a>
2.struts.xml配置 
    <package name="file" namespace="/file" extends="struts-default"> 
        <action name="fileAction" class="com.struts2.file.FileAction">    
            <!-- 下载文件配置 --> 
            <!--type 为 stream 应用 StreamResult 处理--> 
            <result name="down" type="stream"> 
                <!-- 
                        不管实际类型,待下载文件 ContentType 统一指定为 application/octet-stream  
                        默认为 text/plain 
                --> 
                <param name="contentType">application/octet-stream</param> 
                <!--  
                        默认就是 inputStream,它将会指示 StreamResult 通过 inputName 属性值的 getter 方法,               
                        比如这里就是 getInputStream() 来获取下载文件的内容,意味着你的 Action 要有这个方法  
                -->              
                <param name="inputName">inputStream</param> 
                <!--  
                        默认为 inline(在线打开),设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文  
                        件保有存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名,               
                        这里使用的是动态文件名,${fileName}, 它将通过 Action 的 getFileName() 获得文件名  
                -->              
                <param name="contentDisposition">attachment;filename="${fileName}"</param> 
                <!-- 输出时缓冲区的大小 --> 
                <param name="bufferSize">4096</param> 
            </result>             
        </action> 
    </package>
3.Action 
        //Action调用的下载文件方法 
        public String down() { 
                return "down"; 
        } 
         
        //获得下载文件的内容,可以直接读入一个物理文件或从数据库中获取内容 
        public InputStream getInputStream() throws Exception { 
                String dir = servletContext.getRealPath("/file/upload"); 
                File file = new File(dir, "icon.png"); 
                if (file.exists()) { 
                        //下载文件 
                        return new FileInputStream(file); 
                         
                        //和 Servlet 中不一样,这里我们不需对输出的中文转码为 ISO8859-1 
                        //将内容(Struts2 文件下载测试)直接写入文件,下载的文件名必须是文本(txt)类型 
                        //return new ByteArrayInputStream("Struts2 文件下载测试".getBytes()); 
                } 
                return null; 
        } 
 
        // 对于配置中的 ${fileName}, 获得下载保存时的文件名 
        public String getFileName() { 
                String fileName ="图标.png"; 
                try { 
                        // 中文文件名也是需要转码为 ISO8859-1,否则乱码 
                        return new String(fileName.getBytes(), "ISO8859-1"); 
                } catch (UnsupportedEncodingException e) { 
                        return "icon.png"; 
                } 
        }
E. 网上下载的jsp博客文件上传到ftp空间要放在哪个文件夹
你网上下的程序,自己机子上能运行吧?你会在自己机子上运行,就该知道文件放哪里了吧。。。。
你把webroot下的文件全部拷贝到远程虚拟主机的wwwroot中,这里注意程序连接数据库的账号密码,别忘了改成虚拟主机服务商提供给你的。
你应该知道程序用的什么数据库吧,登陆虚拟主机服务商提供给你的IP,账号,密码登陆他提供给你的数据库。将你本地数据库的数据导入到远程数据库。域名解析,登陆。成功!
祝你成功
F. FTP下载用什么工具最好
CuteFTP XP
迅雷(推荐普通用户使用)
此类软件太多了(个人感觉CuteFTP XP还可以)
