用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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值