分享
 
 
 

关于httpclient中MultipartPostMethod类上传文件的一点感受

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

在文件上传过程中碰到很多问题,首先是搞错了类,刚开始时我用的是PostodMethod,以为一个setrequestbody()方法就可以搞定,结果改过来改过去也没改出来什么名堂,最后改用的是MultipartPostMethod类,呵呵,问题解决了,关键点是MultipartPostMethod类里的addParameter()和addPart()两个方法都要用到,而且要注意顺序。不过马上又出现了新的问题,httpclient不支持中文名的文件上传,晕了。又在这上面浪费了一段时间。解决的途径是。找到httpclient3.0\rc\java\org\apache\commons\httpclient\util目录下的EncodingUtil.java,打开,找到文件里面这个地方:

public static byte[] getAsciiBytes(final String data) {

if (data == null) {

throw new IllegalArgumentException("Parameter may not be null"); }

try { return data.getBytes("US-ASCII"); }

catch (UnsupportedEncodingException e) {throw new HttpClientError("HttpClient requires ASCII support"); }

}

看到了没有,return data.getBytes("US-ASCII");它的编码方式是US-ASCII,问题就出在这里了,把这个取掉,换成"GBK"或者"GB2312"保存以后编译,重新运行程序,goooooooooooood。中文名文件现在可以上传了,呵呵

Introducing FileUpload

The FileUpload component has the capability of simplifying the handling of files uploaded to a server. Note that the FileUpload component is meant for use on the server side; in other words, it handles where the files are being uploaded to—not the client side where the files are uploaded from. Uploading files from an HTML form is pretty simple; however, handling these files when they get to the server is not that simple. If you want to apply any rules and store these files based on those rules, things get more difficult.

The FileUpload component remedies this situation, and in very few lines of code you can easily manage the files uploaded and store them in appropriate locations. You will now see an example where you upload some files first using a standard HTML form and then using HttpClient code.

Using HTML File Upload

The commonly used methodology to upload files is to have an HTML form where you define the files you want to upload. A common example of this HTML interface is the Web page you encounter when you want to attach files to an email while using any of the popular Web mail services.

In this example, you will create a simple HTML page where you provide for three files to be uploaded. Listing 1-1 shows the HTML for this page. Note that the enctype attribute for the form has the value multipart/form-data, and the input tag used is of type file. Based on the value of the action attribute, on form submission, the data is sent to ProcessFileUpload.jsp.

Listing 1-1. UploadFiles.html

<HTML>

<HEAD>

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252"/>

<TITLE>File Upload Page</TITLE>

</HEAD>

<BODY>Upload Files

<FORM name="filesForm" action="ProcessFileUpload.jsp"

method="post" enctype="multipart/form-data">

File 1:<input type="file" name="file1"/><br/>

File 2:<input type="file" name="file2"/><br/>

File 3:<input type="file" name="file3"/><br/>

<input type="submit" name="Submit" value="Upload Files"/>

</FORM>

</BODY>

</HTML>

You can use a servlet to handle the file upload. I have used JSP to minimize the code you need to write. The task that the JSP has to accomplish is to pick up the files that are sent as part of the request and store these files on the server. In the JSP, instead of displaying the result of the upload in the Web browser, I have chosen to print messages on the server console so that you can use this same JSP when it is not invoked through an HTML form but by using HttpClient-based code.

Listing 1-2 shows the JSP code. Note the code that checks whether the item is a form field. This check is required because the Submit button contents are also sent as part of the request, and you want to distinguish between this data and the files that are part of the request. You have set the maximum file size to 1,000,000 bytes using the setSizeMax method.

Listing 1-2. ProcessFileUpload.jsp

<%@ page contentType="text/html;charset=windows-1252"%>

<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>

<%@ page import="org.apache.commons.fileupload.FileItem"%>

<%@ page import="jsp servlet ejb .util.List"%>

<%@ page import="jsp servlet ejb .util.Iterator"%>

<%@ page import="jsp servlet ejb .io.File"%>

html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

<title>Process File Upload</title>

</head>

<%

System.out.println("Content Type ="+request.getContentType());

DiskFileUpload fu = new DiskFileUpload();

// If file size exceeds, a FileUploadException will be thrown

fu.setSizeMax(1000000);

List fileItems = fu.parseRequest(request);

Iterator itr = fileItems.iterator();

while(itr.hasNext()) {

FileItem fi = (FileItem)itr.next();

//Check if not form field so as to only handle the file inputs

//else condition handles the submit button input

if(!fi.isFormField()) {

System.out.println("\nNAME: "+fi.getName());

System.out.println("SIZE: "+fi.getSize());

//System.out.println(fi.getOutputStream().toString());

File fNew= new File(application.getRealPath("/"), fi.getName());

System.out.println(fNew.getAbsolutePath());

fi.write(fNew);

}

else {

System.out.println("Field ="+fi.getFieldName());

}

}

%>

<body>

Upload Successful!!

</body>

</html>

CAUTION With FileUpload 1.0 I found that when the form was submitted using Opera version 7.11, the getName method of the class FileItem returns just the name of the file. However, if the form is submitted using Internet Explorer 5.5, the filename along with its entire path is returned by the same method. This can cause some problems.

To run this example, you can use any three files, as the contents of the files are not important. Upon submitting the form using Opera and uploading three random XML files, the output I got on the Tomcat server console was as follows:

Content Type =multipart/form-data; boundary=----------rz7ZNYDVpN1To8L73sZ6OE

NAME: academy.xml

SIZE: 951

D:\javaGizmos\jakarta-tomcat-4.0.1\webapps\HttpServerSideApp\academy.xml

NAME: academyRules.xml

SIZE: 1211

D:\javaGizmos\jakarta-tomcat-4.0.1\webapps\HttpServerSideApp\academyRules.xml

NAME: students.xml

SIZE: 279

D:\javaGizmos\jakarta-tomcat-4.0.1\webapps\HttpServerSideApp\students.xml

Field =Submit

However, when submitting this same form using Internet Explorer 5.5, the output on the server console was as follows:

Content Type =multipart/form-data; boundary=---------------------------7d3bb1de0

2e4

NAME: D:\temp\academy.xml

SIZE: 951

D:\javaGizmos\jakarta-tomcat-4.0.1\webapps\HttpServerSideApp\D:\temp\academy.xml

The browser displayed the following message: “The requested resource (D:\javaGizmos\jakarta-tomcat-4.0.1\webapps\HttpServerSideApp\D:\temp\academy.xml (The filename, directory name, or volume label syntax is incorrect)) is not available.”

This contrasting behavior on different browsers can cause problems. One workaround that I found in an article at http://www.onjava.com/pub/a/onjava/2003/06/25/commons.html is to first create a file reference with whatever is supplied by the getName method and then create a new file reference using the name returned by the earlier file reference. Therefore, you can insert the following code to have your code work with both browsers (I wonder who the guilty party is…blaming Microsoft is always the easy way out)

File tempFileRef = new File(fi.getName());

File fNew = new File(application.getRealPath("/"),tempFileRef.getName());

In this section, you uploaded files using a standard HTML form mechanism. However, often a need arises to be able to upload files from within your jsp servlet ejb code, without any browser or form coming into the picture. In the next section, you will look at HttpClient-based file upload.

Using HttpClient-Based FileUpload

Earlier in the article you saw some of the capabilities of the HttpClient component. One capability I did not cover was its ability to send multipart requests. In this section, you will use this capability to upload a few files to the same JSP that you used for uploads using HTML.

The class org.apache.commons.httpclient.methods.MultipartPostMethod provides the multipart method capability to send multipart-encoded forms, and the package org.apache.commons.httpclient.methods.multipart has the support classes required. Sending a multipart form using HttpClient is quite simple. In the code in Listing 1-3, you send three files to ProcessFileUpload.jsp.

Listing 1-3. HttpMultiPartFileUpload.java

package com.commonsbook.chap9;

import jsp servlet ejb .io.File;

import jsp servlet ejb .io.IOException;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.methods.MultipartPostMethod;

public class HttpMultiPartFileUpload {

private static String url =

"http://localhost/yaoliang/ProcessFileUpload.jsp[url=http://localhost/HttpServerSideApp/ProcessFileUpload.jsp][/url]";

public static void main(String[] args) throws IOException {

HttpClient client = new HttpClient();

MultipartPostMethod mPost = new MultipartPostMethod(url);

client.setConnectionTimeout(8000);

// Send any XML file as the body of the POST request

File f1 = new File("D:/students.xml");

File f2 = new File("D:/demy.xml");

File f3 = new File("D:/demyRules.xml");

System.out.println("File1 Length = " + f1.length());

System.out.println("File2 Length = " + f2.length());

System.out.println("File3 Length = " + f3.length());

mPost.addParameter(f1.getName(),f1.getName(), f1);

mPost.addParameter(f2.getName(), f2.getName(), f2);

mPost.addParameter(f3.getName(), f3.getName(),f3);

FilePart part1 = new FilePart("file1",file);

FilePart part2 = new FilePart("file2",file);

FilePart part3 = new FilePart("file3",file);

mPost.addPart(part1);

mPost.addPart(part2);

mPost.addPart(part3);

int statusCode1 = client.executeMethod(mPost);

System.out.println("statusLine>>>" + mPost.getStatusLine());

mPost.releaseConnection();

}

}

In this code, you just add the files as parameters and execute the method. The ProcessFileUpload.jsp file gets invoked, and the output is as follows:

Content Type =multipart/form-data; boundary=----------------31415926535897932384

6

NAME: students.xml

SIZE: 279

D:\javaGizmos\jakarta-tomcat-4.0.1\webapps\HttpServerSideApp\students.xml

NAME: academy.xml

SIZE: 951

D:\javaGizmos\jakarta-tomcat-4.0.1\webapps\HttpServerSideApp\academy.xml

NAME: academyRules.xml

SIZE: 1211

D:\javaGizmos\jakarta-tomcat-4.0.1\webapps\HttpServerSideApp\academyRules.xml

Thus, file uploads on the server side become quite a simple task if you are using the Commons FileUpload component.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有