`
zhengshuangxi1226
  • 浏览: 50439 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

用commons的HttpClient和FileUpload写的文件上传下载

阅读更多
public class FileUploader {  
 
    private ClientAppLogger appLogger = ClientAppLogger.getInstance();  
    private String servletUrl;  
 
    public FileUploader(String servletUrl) {  
        this.servletUrl = servletUrl;  
    }  
 
    public void upload(NameValuePair pair, File[] files)  
        throws FileUploadException {  
        PostMethod p = new PostMethod(servletUrl);  
        try {  
            //设置param  
            String[][] attrs = pair.getAttributes();  
            appLogger.debug("AttrLen=" + attrs.length);  
            Part[] params = new Part[attrs.length + files.length];  
            for (int i = 0; i < attrs.length; i++) {  
                StringPart stringPart = new StringPart(attrs[i][0],  
                                               attrs[i][1]);  
                //中文要用这个  
                stringPart.setCharSet("GBK");  
                params[i] = stringPart;  
            }  
            for (int i = 0; i < files.length; i++) {  
                FilePart filePart = new FilePart(files[i].getName(), files[i]);  
 
                filePart.setCharSet("GBK");  
                params[attrs.length + i] = filePart;  
            }  
 
            MultipartRequestEntity post =  
                new MultipartRequestEntity(params, p.getParams());  
 
            p.setRequestEntity(post);  
 
            HttpClient client = new HttpClient();  
            client.getHttpConnectionManager().  
                getParams().setConnectionTimeout(5000);  
            int result = client.executeMethod(p);  
            if (result == 200) {  
                System.out.println("Upload File OK");  
            } else {  
                String error = "File Upload Error HttpCode=" + result;  
                appLogger.error(error);  
                throw new FileUploadException(error);  
            }  
        } catch (IOException e) {  
            appLogger.error("File Upload Error", e);  
            throw new FileUploadException(e);  
        } finally {  
            p.releaseConnection();  
        }  
    }  

public class FileUploader {

    private ClientAppLogger appLogger = ClientAppLogger.getInstance();
    private String servletUrl;

    public FileUploader(String servletUrl) {
        this.servletUrl = servletUrl;
    }

    public void upload(NameValuePair pair, File[] files)
        throws FileUploadException {
        PostMethod p = new PostMethod(servletUrl);
        try {
            //设置param
            String[][] attrs = pair.getAttributes();
            appLogger.debug("AttrLen=" + attrs.length);
            Part[] params = new Part[attrs.length + files.length];
            for (int i = 0; i < attrs.length; i++) {
                StringPart stringPart = new StringPart(attrs[i][0],
                                               attrs[i][1]);
                //中文要用这个
                stringPart.setCharSet("GBK");
                params[i] = stringPart;
            }
            for (int i = 0; i < files.length; i++) {
                FilePart filePart = new FilePart(files[i].getName(), files[i]);

                filePart.setCharSet("GBK");
                params[attrs.length + i] = filePart;
            }

            MultipartRequestEntity post =
                new MultipartRequestEntity(params, p.getParams());

            p.setRequestEntity(post);

            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().
                getParams().setConnectionTimeout(5000);
            int result = client.executeMethod(p);
            if (result == 200) {
                System.out.println("Upload File OK");
            } else {
                String error = "File Upload Error HttpCode=" + result;
                appLogger.error(error);
                throw new FileUploadException(error);
            }
        } catch (IOException e) {
            appLogger.error("File Upload Error", e);
            throw new FileUploadException(e);
        } finally {
            p.releaseConnection();
        }
    }
}

2.UploadServlet.java

view plaincopy to clipboardprint?
public class UploadServlet  
    extends HttpServlet {  
    private ServletConfig config;  
    private ServerAppLogger appLogger; //应用程序日志  
    protected String uploadPath; //上传路径  
 
    public void init(ServletConfig config)  
        throws ServletException {  
        this.config = config;  
        String uploadDir = config.getServletContext().getInitParameter("UploadPath");  
        this.uploadPath = uploadDir;  
        appLogger = ServerAppLogger.getInstance();  
        String name = Thread.currentThread().getName();  
        name = "[" + name + "]";  
        appLogger.info("UploadPath=" + uploadPath);  
        appLogger.info(name + "####Init UploadServlet Successfully####");  
    }  
 
    public void destroy() {  
        String name = Thread.currentThread().getName();  
        name = "[" + name + "]";  
        appLogger.info(name + "####Remove UploadServlet Successfully####");  
    }  
 
    public void doGet(HttpServletRequest httpReq, HttpServletResponse httpResp)  
        throws 
        ServletException, IOException {  
        doPost(httpReq, httpResp);  
    }  
 
    public void doPost(HttpServletRequest httpReq, HttpServletResponse httpResp)  
        throws ServletException, IOException {  
        processUpload(httpReq, httpResp);  
    }  
 
    protected void processUpload(HttpServletRequest httpReq, HttpServletResponse httpResp)  
        throws ServletException {  
        MultipartParser parser = new MultipartParser();  
        parser.parseAndSaveFiles(uploadPath, httpReq);  
        File[] files = parser.getFiles();  
        NameValuePair params = parser.getParams();  
        processOther(params, files, httpReq, httpResp);  
    }  
 
    protected void processOther(NameValuePair params,  
                                File[] savedFiles,  
                                HttpServletRequest httpReq,  
                                HttpServletResponse httpResp)  
        throws ServletException {  
        String name = Thread.currentThread().getName();  
        name = "[" + name + "]";  
        appLogger.debug(name +  
                        "Upload processOther, " +  
                        "if you want to change the behaviour, " +  
                        "please override this method!");  
        printDebugInfo(params, savedFiles);  
    }  
 
    private void printDebugInfo(NameValuePair params,  
                                File[] savedFiles) {  
        String name = Thread.currentThread().getName();  
        name = "[" + name + "]";  
 
        StringBuffer buffer = new StringBuffer();  
        buffer.append("Print parameters:\n");  
        String[][] attrs = params.getAttributes();  
        for (int i = 0; i < attrs.length; i++) {  
            String key = attrs[i][0];  
            String value = attrs[i][1];  
            buffer.append("Key=" + key + ";Value=" + value + "\n");  
        }  
        appLogger.debug(name + buffer.toString());  
 
        buffer = new StringBuffer();  
        buffer.append("Print saved filename:\n");  
        for (int i = 0; i < savedFiles.length; i++) {  
            String fileName = savedFiles[i].getAbsolutePath();  
            buffer.append("SavedFileName=" + fileName + "\n");  
        }  
        appLogger.debug(name + buffer.toString());  
    }  

public class UploadServlet
    extends HttpServlet {
    private ServletConfig config;
    private ServerAppLogger appLogger; //应用程序日志
    protected String uploadPath; //上传路径

    public void init(ServletConfig config)
        throws ServletException {
        this.config = config;
        String uploadDir = config.getServletContext().getInitParameter("UploadPath");
        this.uploadPath = uploadDir;
        appLogger = ServerAppLogger.getInstance();
        String name = Thread.currentThread().getName();
        name = "[" + name + "]";
        appLogger.info("UploadPath=" + uploadPath);
        appLogger.info(name + "####Init UploadServlet Successfully####");
    }

    public void destroy() {
        String name = Thread.currentThread().getName();
        name = "[" + name + "]";
        appLogger.info(name + "####Remove UploadServlet Successfully####");
    }

    public void doGet(HttpServletRequest httpReq, HttpServletResponse httpResp)
        throws
        ServletException, IOException {
        doPost(httpReq, httpResp);
    }

    public void doPost(HttpServletRequest httpReq, HttpServletResponse httpResp)
        throws ServletException, IOException {
        processUpload(httpReq, httpResp);
    }

    protected void processUpload(HttpServletRequest httpReq, HttpServletResponse httpResp)
        throws ServletException {
        MultipartParser parser = new MultipartParser();
        parser.parseAndSaveFiles(uploadPath, httpReq);
        File[] files = parser.getFiles();
        NameValuePair params = parser.getParams();
        processOther(params, files, httpReq, httpResp);
    }

    protected void processOther(NameValuePair params,
                                File[] savedFiles,
                                HttpServletRequest httpReq,
                                HttpServletResponse httpResp)
        throws ServletException {
        String name = Thread.currentThread().getName();
        name = "[" + name + "]";
        appLogger.debug(name +
                        "Upload processOther, " +
                        "if you want to change the behaviour, " +
                        "please override this method!");
        printDebugInfo(params, savedFiles);
    }

    private void printDebugInfo(NameValuePair params,
                                File[] savedFiles) {
        String name = Thread.currentThread().getName();
        name = "[" + name + "]";

        StringBuffer buffer = new StringBuffer();
        buffer.append("Print parameters:\n");
        String[][] attrs = params.getAttributes();
        for (int i = 0; i < attrs.length; i++) {
            String key = attrs[i][0];
            String value = attrs[i][1];
            buffer.append("Key=" + key + ";Value=" + value + "\n");
        }
        appLogger.debug(name + buffer.toString());

        buffer = new StringBuffer();
        buffer.append("Print saved filename:\n");
        for (int i = 0; i < savedFiles.length; i++) {
            String fileName = savedFiles[i].getAbsolutePath();
            buffer.append("SavedFileName=" + fileName + "\n");
        }
        appLogger.debug(name + buffer.toString());
    }
}

3.FileDownloader.java

view plaincopy to clipboardprint?
public class FileDownloader {  
 
    private ClientAppLogger appLogger = ClientAppLogger.getInstance();  
    private String servletUrl;  
 
    public FileDownloader(String servletUrl) {  
        this.servletUrl = servletUrl;  
    }  
 
    public void download(NameValuePair pair, String fileSavePath)  
        throws FileDownloadException {  
        BufferedInputStream in = null;  
        BufferedOutputStream out = null;  
        PostMethod p = new PostMethod(servletUrl);  
        try {  
            //设置param  
            String[][] attrs = pair.getAttributes();  
            Part[] params = new Part[attrs.length];  
            for (int i = 0; i < attrs.length; i++) {  
                StringPart pt = new StringPart(attrs[i][0],  
                                               attrs[i][1]);  
                //中文要用这个  
                pt.setCharSet("GBK");  
                params[i] = pt;  
            }  
 
            MultipartRequestEntity post =  
                new MultipartRequestEntity(params, p.getParams());  
 
            p.setRequestEntity(post);  
 
            HttpClient client = new HttpClient();  
            client.getHttpConnectionManager().  
                getParams().setConnectionTimeout(5000);  
            int result = client.executeMethod(p);  
            if (result == 200) {  
                in = new BufferedInputStream(p.getResponseBodyAsStream());  
                File file = new File(fileSavePath);  
                out = new BufferedOutputStream(new FileOutputStream(file));  
                byte[] buffer = new byte[1024];  
                int len = -1;  
                while ((len = in.read(buffer, 0, 1024)) > -1) {  
                    out.write(buffer, 0 , len);  
                }  
                System.out.println("Download File OK");  
            } else {  
                String error = "File Download Error HttpCode=" + result;  
                appLogger.error(error);  
                throw new FileDownloadException(error);  
            }  
        } catch (IOException e) {  
            appLogger.error("File Download Error", e);  
            throw new FileDownloadException(e);  
        } finally {  
            p.releaseConnection();  
            try {  
                if (in != null) {  
                    in.close();  
                }  
                if (out != null) {  
                    out.close();  
                }  
            } catch (IOException ex) {  
            }  
        }  
    }  

public class FileDownloader {

    private ClientAppLogger appLogger = ClientAppLogger.getInstance();
    private String servletUrl;

    public FileDownloader(String servletUrl) {
        this.servletUrl = servletUrl;
    }

    public void download(NameValuePair pair, String fileSavePath)
        throws FileDownloadException {
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        PostMethod p = new PostMethod(servletUrl);
        try {
            //设置param
            String[][] attrs = pair.getAttributes();
            Part[] params = new Part[attrs.length];
            for (int i = 0; i < attrs.length; i++) {
                StringPart pt = new StringPart(attrs[i][0],
                                               attrs[i][1]);
                //中文要用这个
                pt.setCharSet("GBK");
                params[i] = pt;
            }

            MultipartRequestEntity post =
                new MultipartRequestEntity(params, p.getParams());

            p.setRequestEntity(post);

            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().
                getParams().setConnectionTimeout(5000);
            int result = client.executeMethod(p);
            if (result == 200) {
                in = new BufferedInputStream(p.getResponseBodyAsStream());
                File file = new File(fileSavePath);
                out = new BufferedOutputStream(new FileOutputStream(file));
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = in.read(buffer, 0, 1024)) > -1) {
                    out.write(buffer, 0 , len);
                }
                System.out.println("Download File OK");
            } else {
                String error = "File Download Error HttpCode=" + result;
                appLogger.error(error);
                throw new FileDownloadException(error);
            }
        } catch (IOException e) {
            appLogger.error("File Download Error", e);
            throw new FileDownloadException(e);
        } finally {
            p.releaseConnection();
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ex) {
            }
        }
    }
}

4.DownloadServlet.java



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/gtuu0123/archive/2009/06/26/4299779.aspx
分享到:
评论

相关推荐

    httpclient 上传文件

    下面是一个简单的示例代码,展示了如何使用HTTPClient和FileUpload上传文件: ```java import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org....

    HttpClient上传文件 Servlet 处理文件上传

    HttpClient 上传文件 Servlet 处理文件上传 commons-fileupload 处理文件上传 commons-fileupload 处理文件上传,在struts中可以不用对应actionform,在jsp,servelet中应用都很方便

    上传文件的jar包 commons-io commons-fileupload.jar

    `commons-io`和`commons-fileupload`是Apache开源组织提供的两个非常重要的库,它们为文件上传提供了强大的支持。这两个库结合使用,可以帮助开发者轻松地处理文件上传的细节。 `commons-io`库主要提供了各种I/O...

    httpClient上传文件

    - 创建`FilePart`对象,传入文件名和文件本身。 - 将`FilePart`对象作为数组`Part[]`的一部分,传递给`MultipartRequestEntity`构造函数,设置POST请求的实体。 - 设置连接超时时间,防止在网络不稳定时等待过久...

    httpclient上传文件

    本篇文章将详细介绍如何使用Commons HttpClient进行文件上传。 一、Apache Commons HttpClient简介 Apache Commons HttpClient是一个强大的HTTP客户端API,它提供了丰富的功能,如连接管理、重试机制、身份验证等。...

    四个jar包commons-beanutils-1.8.3+dbcp+dbutils-1.4+commons-fileupload-1.2.2

    BeanUtils用于处理对象属性,DBCP和DBUtils为数据库操作提供便利,而FileUpload则解决了文件上传的需求。将这些库整合进项目中,可以显著提高代码的可读性和维护性,同时减少重复工作,提升整体项目的稳定性和效率。...

    httpClient

    在实际使用中,开发者需要理解每个库的核心概念和API,比如HttpClient中的`HttpClient`对象,`GetMethod`和`PostMethod`,以及FileUpload中的`FileItemFactory`和`ServletFileUpload`。同时,熟悉如何使用Commons IO...

    commons.io.jar大合集必备httpcore-4.3.jar和commons.fileupload.jar和httpclient-4.3.1.jar

    commons.io.jar大合集通用必备httpcore-4.3.jar和commons.fileupload.jar和faceppsdk.jar和httpclient-4.3.1.jar 可以做人脸识别 全新!学习的必备JAR包!

    ssh文件上传下载,很简答的东西

    总的来说,SSH文件上传下载涉及网络协议、加密安全、编程接口等多个方面,理解并熟练运用这些工具和技术,能够帮助开发者在不安全的网络环境中安全高效地处理文件传输任务。在实际开发中,结合Struts、Spring和...

    java 文件上传下载 断点续传 断点上传

    在Java开发中,文件上传和下载是常见的功能需求,尤其在Web应用中更是如此。...而提供的"uploadFile"可能就是实现这些功能的源代码,可以作为参考和学习的对象,进一步理解并实践文件上传下载的实现细节。

    上传文件代码段

    5. **Apache Commons BeanUtils** (commons-beanutils.jar): 提供了JavaBean属性操作的便捷方法,简化了对象属性的设置和获取,如果文件上传涉及到对象模型,这个库会很有帮助。 6. **Apache Commons DBCP** ...

    jakarta-commons 相关依赖包

    jakarta-commons 相关依赖包,文件列表: commons-attributes-api.jar commons-attributes-compiler.jar commons-beanutils.jar commons-codec.jar commons-collections.jar commons-dbcp.jar commons-digester.jar ...

    org.apache.commons jar包

    7. **Commons FileUpload**:专门用于处理HTTP请求中的文件上传,简化了文件上传的处理逻辑。 8. **Commons JDBC**:提供了数据库操作的辅助工具,如数据库连接池、SQL执行等。 9. **Commons Math**:提供了基础...

    apache-commons源码及jar文件

    FileUpload 使得在你可以在应用和Servlet中容易的加入强大和高性能的文件上传能力 HttpClient Commons-HttpClient 提供了可以工作于HTTP协议客户端的一个框架. IO IO 是一个 I/O 工具集 Jelly Jelly是一个基于 ...

    org.apache.commons 常用jar 以及部分源码

    以下是压缩文件的jar包名称: commons-validator-1.3.0.jar commons-pool-1.3.jar commons-net-3.0.jar commons-logging-api-1.1.jar commons-logging-1.0.4.jar commons-lang-2.1.jar commons-io-1.3.2.jar commons...

    commons-jar合集

    9. **Commons FileUpload**: 用于处理HTTP请求中的文件上传,简化了接收大文件和多个文件的上传操作。 10. **Commons Configuration**: 提供了一种灵活的方式来读取和管理配置信息,支持从不同来源(如文件、系统...

    spring-aop-2.5.6.jar,jfreechart-1.0.13.jar,commons-fileupload.jar,

    Commons FileUpload库简化了这一过程,处理了文件大小限制、多部分表单数据解析等问题,使得开发者能更安全、高效地实现文件上传功能。 4. **JSTL**: JSP Standard Tag Library,即JSTL,是一组标准标签库,用于...

    javaweb文件上传和下载需要导入的包

    `org.apache.commons.fileupload` 和 `org.apache.commons.io` 包:Apache Commons FileUpload库处理文件上传,它能解析multipart/form-data类型的请求,将上传的文件保存到服务器。`IO`库则提供了一些通用的I/O...

    Apache Commons 所有包最新版本 含SRC (6/7)

    1.1-bin.zip commons-email-1.1-src.zip commons-fileupload-1.2.1-bin.zip commons-fileupload-1.2.1-src.zip commons-io-1.4-bin.zip commons-io-1.4-src.zip commons-jci-1.0-bin.zip ...

    Android的HttpClient开发实例

    本开发实例将带你深入理解如何在Android项目中使用`HttpClient`进行网络请求,实现数据的获取和上传。 首先,`HttpClient`是Apache的一个开源项目,它提供了一个强大的API来处理HTTP协议。`commons-httpclient-3.1....

Global site tag (gtag.js) - Google Analytics