`

http,ftp实现上传和下载(上)

阅读更多
ftp是应用层的协议,即文件传输协议。默认使用21端口。通过该协议可以实现远程主机文件的上传和下载。
实现文件上传和下载通常使用2中方式:基于ftp的上传和下载和基于http协议的上传和下载
一、htpp协议实现文件上传
1)定义上传表单
<%--
encType="multipart/form-data"是设定表单的mime编码,表示是使用2进制传送表单数据,只有使用这种方式才能上传文件
--%>
<form method="post" action="处理url" encType="multipart/form-data" align="center">
     <table>
        <tr>
           <td>软件描述:<input type="text" name="soft.desc"></td>
        </tr>
        <tr>
           <td>上传文件:<input type="file" name="soft.upload"></td>
        </tr>
        <tr>
           <td><input type="submit" value="提交">
        </tr>
     </table>  
</form>
2)定义上传类
public class Soft{
     //接收文件需要定义3个约定好的属性字段
      private File upload;
     private String uploadContentType;
     private String uploadFileName;
     //省略get和set方法     
}
2)Struts2 action中处理上传文件
public class UploadAction{
     private Soft soft;
     //定义保存文件路径
      private String savePath;
    
     public String execute() throws Exception{
     //定义FileOutputStream用于写文件
      FileOutputStream fos = null;
     //定义 FileInputStream 用于读取文件
      FileInputStream fis = null;
    try{   
      fos = new FileOutputStream(savePath+soft.getUploadFileName());
      fis = new FileInputStream(soft.getUpload());
      int length  = 0;
      byte[] buffer= new bytes[1024];
      while(length=fis.read(buffer)>0){
      fos.write(buffer,0,length);    
    }
     return SUCESS;
    }catch(Exception e){
    log.error(e.getMessage);
    return ERROR;
}finally{
    //关闭IO
}
}
}
二、htpp协议实现文件下载
通常的http下载只需要在超链接中链接下载资源的服务器地址即可。
若是需要进行虚拟映射可以通过tomcat中配置
<Context  path="/project/image"  docBase="服务器文件真是目录"  debug="0"    reloadable="true"  crossContext="true"/>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics