用commons的HttpClient和FileUpload写的文件上传下载类
其中主要几个类如下:
1.FieUploader.java
view plaincopy to clipboardprint?
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
view plaincopy to clipboardprint?
public class DownloadServlet
extends HttpServlet {
private ServletConfig config;
private ServerAppLogger appLogger; //应用程序日志
protected String downloadPath; //下载路径
public void init(ServletConfig config)
throws ServletException {
this.config = config;
String downloadDir = config.getServletContext().getInitParameter("UploadPath");
this.downloadPath = downloadDir;
appLogger = ServerAppLogger.getInstance();
String name = Thread.currentThread().getName();
name = "[" + name + "]";
appLogger.info("DownloadPath=" + downloadPath);
appLogger.info(name + "####Init DownloadServlet Successfully####");
}
public void destroy() {
String name = Thread.currentThread().getName();
name = "[" + name + "]";
appLogger.info(name + "####Remove DownloadServlet Successfully####");
}
public void doGet(HttpServletRequest httpReq, HttpServletResponse httpResp)
throws
ServletException, IOException {
doPost(httpReq, httpResp);
}
public void doPost(HttpServletRequest httpReq, HttpServletResponse httpResp)
throws ServletException, IOException {
processDownload(httpReq, httpResp);
}
protected void processDownload(HttpServletRequest httpReq, HttpServletResponse httpResp)
throws ServletException {
MultipartParser parser = new MultipartParser();
parser.parseAndSaveFiles(downloadPath, httpReq);
NameValuePair params = parser.getParams();
printDebugInfo(params);
processOther(params, httpReq, httpResp);
String fileName = getDownFileName(params);
processDownloadFile(fileName, httpReq, httpResp);
}
protected void processDownloadFile(String fileName,
HttpServletRequest httpReq,
HttpServletResponse httpResp)
throws ServletException {
File file = new File(downloadPath, fileName);
appLogger.debug("fileName=" + fileName);
appLogger.debug("fileLength=" + file.length());
BufferedOutputStream output = null;
BufferedInputStream input = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
output = new BufferedOutputStream(bos);
input = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[4096];
int n = -1;
while ((n = input.read(buffer, 0, 4096)) > -1) {
appLogger.debug("n=" + n);
output.write(buffer, 0, n);
}
/**
* 此处必须调用flush
* 如果文件大小小于4096,那么由于数据都在buffer中,
* 因此BufferedOutputStream内部的ByteArrayOutputStream
* 根本没有得到数据,因此其长度返回0
*/
output.flush();
appLogger.debug("ByteArrayLen=" + bos.size());
httpResp.getOutputStream().write(bos.toByteArray());
httpResp.getOutputStream().flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
output.close();
} catch (IOException e) {}
}
}
protected String getDownFileName(NameValuePair params)
throws ServletException {
String fileName = params.getAttribute("filename");
if (fileName == null) {
throw new ServletException("Please set filename parameter in request");
}
return fileName;
}
protected void processOther(NameValuePair params,
HttpServletRequest httpReq,
HttpServletResponse httpResp)
throws ServletException {
String name = Thread.currentThread().getName();
name = "[" + name + "]";
appLogger.debug(name +
"Download processOther, " +
"if you want to change the behaviour, " +
"please override this method!");
}
private void printDebugInfo(NameValuePair params) {
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());
}
}
public class DownloadServlet
extends HttpServlet {
private ServletConfig config;
private ServerAppLogger appLogger; //应用程序日志
protected String downloadPath; //下载路径
public void init(ServletConfig config)
throws ServletException {
this.config = config;
String downloadDir = config.getServletContext().getInitParameter("UploadPath");
this.downloadPath = downloadDir;
appLogger = ServerAppLogger.getInstance();
String name = Thread.currentThread().getName();
name = "[" + name + "]";
appLogger.info("DownloadPath=" + downloadPath);
appLogger.info(name + "####Init DownloadServlet Successfully####");
}
public void destroy() {
String name = Thread.currentThread().getName();
name = "[" + name + "]";
appLogger.info(name + "####Remove DownloadServlet Successfully####");
}
public void doGet(HttpServletRequest httpReq, HttpServletResponse httpResp)
throws
ServletException, IOException {
doPost(httpReq, httpResp);
}
public void doPost(HttpServletRequest httpReq, HttpServletResponse httpResp)
throws ServletException, IOException {
processDownload(httpReq, httpResp);
}
protected void processDownload(HttpServletRequest httpReq, HttpServletResponse httpResp)
throws ServletException {
MultipartParser parser = new MultipartParser();
parser.parseAndSaveFiles(downloadPath, httpReq);
NameValuePair params = parser.getParams();
printDebugInfo(params);
processOther(params, httpReq, httpResp);
String fileName = getDownFileName(params);
processDownloadFile(fileName, httpReq, httpResp);
}
protected void processDownloadFile(String fileName,
HttpServletRequest httpReq,
HttpServletResponse httpResp)
throws ServletException {
File file = new File(downloadPath, fileName);
appLogger.debug("fileName=" + fileName);
appLogger.debug("fileLength=" + file.length());
BufferedOutputStream output = null;
BufferedInputStream input = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
output = new BufferedOutputStream(bos);
input = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[4096];
int n = -1;
while ((n = input.read(buffer, 0, 4096)) > -1) {
appLogger.debug("n=" + n);
output.write(buffer, 0, n);
}
/**
* 此处必须调用flush
* 如果文件大小小于4096,那么由于数据都在buffer中,
* 因此BufferedOutputStream内部的ByteArrayOutputStream
* 根本没有得到数据,因此其长度返回0
*/
output.flush();
appLogger.debug("ByteArrayLen=" + bos.size());
httpResp.getOutputStream().write(bos.toByteArray());
httpResp.getOutputStream().flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
output.close();
} catch (IOException e) {}
}
}
protected String getDownFileName(NameValuePair params)
throws ServletException {
String fileName = params.getAttribute("filename");
if (fileName == null) {
throw new ServletException("Please set filename parameter in request");
}
return fileName;
}
protected void processOther(NameValuePair params,
HttpServletRequest httpReq,
HttpServletResponse httpResp)
throws ServletException {
String name = Thread.currentThread().getName();
name = "[" + name + "]";
appLogger.debug(name +
"Download processOther, " +
"if you want to change the behaviour, " +
"please override this method!");
}
private void printDebugInfo(NameValuePair params) {
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());
}
}
5.MultipartParser.java
view plaincopy to clipboardprint?
public class MultipartParser {
private File[] saveFiles;
private NameValuePair params;
private boolean flag = false;
public MultipartParser() {
}
public void parseAndSaveFiles(String uploadPath,
HttpServletRequest httpReq)
throws ServletException {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
factory.setRepository(new File(uploadPath)); // 设置缓冲区目录
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(10 * 1024 * 1024); // 设置最大文件尺寸,这里是10MB
List items = upload.parseRequest(httpReq); // 得到所有的文件和参数
Iterator iter = items.iterator();
Vector fieldsVector = new Vector();
Vector fileVector = new Vector();
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
if (item.isFormField()) { //simple form field
fieldsVector.add(item);
} else {
String fileName = item.getName();
IFileNameStrategy strategy = new MillSecondFileNameStrategy();
fileName = strategy.convertFileName(fileName);
File savedFile = new File(uploadPath, fileName);
item.write(savedFile);
fileVector.add(savedFile);
}
}
saveFiles = new File[fileVector.size()];
for (int i = 0; i < fileVector.size(); i++) {
saveFiles[i] = (File)fileVector.get(i);
}
params = new NameValuePair();
for (int i = 0; i < fieldsVector.size(); i++) {
FileItem item = (FileItem)fieldsVector.get(i);
String key = item.getFieldName();
String value = item.getString();
params.addAttribute(key, value);
}
flag = true;
} catch (Exception e) {
throw new ServletException(e);
}
}
public NameValuePair getParams() {
checkState();
return params;
}
public File[] getFiles() {
checkState();
return saveFiles;
}
private void checkState() {
if (!flag) {
throw new IllegalStateException("Please call parseAndSaveFiles() first");
}
}
}
public class MultipartParser {
private File[] saveFiles;
private NameValuePair params;
private boolean flag = false;
public MultipartParser() {
}
public void parseAndSaveFiles(String uploadPath,
HttpServletRequest httpReq)
throws ServletException {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
factory.setRepository(new File(uploadPath)); // 设置缓冲区目录
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(10 * 1024 * 1024); // 设置最大文件尺寸,这里是10MB
List items = upload.parseRequest(httpReq); // 得到所有的文件和参数
Iterator iter = items.iterator();
Vector fieldsVector = new Vector();
Vector fileVector = new Vector();
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
if (item.isFormField()) { //simple form field
fieldsVector.add(item);
} else {
String fileName = item.getName();
IFileNameStrategy strategy = new MillSecondFileNameStrategy();
fileName = strategy.convertFileName(fileName);
File savedFile = new File(uploadPath, fileName);
item.write(savedFile);
fileVector.add(savedFile);
}
}
saveFiles = new File[fileVector.size()];
for (int i = 0; i < fileVector.size(); i++) {
saveFiles[i] = (File)fileVector.get(i);
}
params = new NameValuePair();
for (int i = 0; i < fieldsVector.size(); i++) {
FileItem item = (FileItem)fieldsVector.get(i);
String key = item.getFieldName();
String value = item.getString();
params.addAttribute(key, value);
}
flag = true;
} catch (Exception e) {
throw new ServletException(e);
}
}
public NameValuePair getParams() {
checkState();
return params;
}
public File[] getFiles() {
checkState();
return saveFiles;
}
private void checkState() {
if (!flag) {
throw new IllegalStateException("Please call parseAndSaveFiles() first");
}
}
}
说明:
NameValuePair类,只是一个Map,用于存一般的请求参数
IFileNameStrategy,是一个接口,用于在服务器上存储时转换文件名(防止重名),其只有一个方法convertFileName
FileUploader和FileDownloader是在客户端用,FileDownloader中的NameValuePair中要传入filename参数
UploadServlet和DownloadServlet部署在服务器上,其中有几个方法,如processOther可以被子类重写以加入新行为
客户端调用代码如下:
upload:
view plaincopy to clipboardprint?
//读配置文件
File file = ResourseLoader.getFileFromJar("ServletConfig.properties",this.getClass());
Properties props = new Properties();
String uploadServlet = "";
try {
props.load(new FileInputStream(file));
uploadServlet = props.getProperty("UploadUrl");
} catch (IOException ex) {
ex.printStackTrace();
}
FileUploader uploader = new FileUploader(uploadServlet);
NameValuePair pair = new NameValuePair();
pair.addAttribute("user", "abcd");
pair.addAttribute("pwd", "1234");
String tempDir = System.getProperty("java.io.tmpdir");
File[] files = new File[5];
for (int i = 0; i < files.length; i++) {
files[i] = new File(tempDir + i + ".tmp");
try {
files[i].createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
uploader.upload(pair, files);
} catch (FileUploadException ex) {
logger.error("#File Upload Error#", ex);
}
//读配置文件
File file = ResourseLoader.getFileFromJar("ServletConfig.properties",this.getClass());
Properties props = new Properties();
String uploadServlet = "";
try {
props.load(new FileInputStream(file));
uploadServlet = props.getProperty("UploadUrl");
} catch (IOException ex) {
ex.printStackTrace();
}
FileUploader uploader = new FileUploader(uploadServlet);
NameValuePair pair = new NameValuePair();
pair.addAttribute("user", "abcd");
pair.addAttribute("pwd", "1234");
String tempDir = System.getProperty("java.io.tmpdir");
File[] files = new File[5];
for (int i = 0; i < files.length; i++) {
files[i] = new File(tempDir + i + ".tmp");
try {
files[i].createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
uploader.upload(pair, files);
} catch (FileUploadException ex) {
logger.error("#File Upload Error#", ex);
}
download:
view plaincopy to clipboardprint?
File file = ResourseLoader.getFileFromJar("ServletConfig.properties",
this.getClass());
Properties props = new Properties();
String downloadServlet = "";
try {
props.load(new FileInputStream(file));
downloadServlet = props.getProperty("DownloadUrl");
} catch (IOException ex) {
ex.printStackTrace();
}
FileDownloader downloader = new FileDownloader(downloadServlet);
NameValuePair pair = new NameValuePair();
pair.addAttribute("user", "abcd");
pair.addAttribute("pwd", "123");
pair.addAttribute("filename", "YServer.txt");
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("请输入文件名");
chooser.setMultiSelectionEnabled(false);
int result = chooser.showSaveDialog(frmUserManager);
if (result == JFileChooser.APPROVE_OPTION) {
String filePath =
chooser.getSelectedFile().getAbsolutePath();
try {
downloader.download(pair, filePath);
} catch (FileDownloadException ex) {
logger.error("#File Download Error#", ex);
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/gtuu0123/archive/2009/06/26/4299779.aspx