commons-upload 和 httpcomponent 客户端的 ContentType 问题
我正在尝试开发一个使用 httpcomponents 上传文件的 Http 客户端:
HttpPost httppost = new HttpPost(myURL);
httppost.setHeader("Content-type",
"multipart/form-data; boundary=stackoverflow");
httppost.setHeader("Accept", "text/xml");
MultipartEntity reqEntity = new multipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE,"stackoverflow",
Charset.forName("UTF-8"));
FileBody bin = new FileBody(myFile);
reqEntity.addPart("File", bin);
httppost.setEntity(reqEntity);
HttpResponse response = client.execute(httppost);
在服务器端,有一种
doPost(HttpServletRequest request, HttpServletResponse response)
解析请求的方法:
FileItemFactory factory = new DiskFileItemFactory(204800, new File(
uploadDirectory));
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
List<FileItem> items = fileUpload.parseRequest(request);
Iterator<FileItem> itemIterator = items.iterator();
while (itemIterator.hasNext()) {
FileItem item = itemIterator.next();
....
它工作正常,但问题是我的 FileItem 的 Content-type 为 null,并且稍后出现 NullPointerException。但是,当我在客户端执行 bin.getContentType() 时,我得到“text/xml”。
有人知道此内容类型何时丢失以及如何修复吗?
I am trying to develop a Http client which uploads a file with httpcomponents:
HttpPost httppost = new HttpPost(myURL);
httppost.setHeader("Content-type",
"multipart/form-data; boundary=stackoverflow");
httppost.setHeader("Accept", "text/xml");
MultipartEntity reqEntity = new multipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE,"stackoverflow",
Charset.forName("UTF-8"));
FileBody bin = new FileBody(myFile);
reqEntity.addPart("File", bin);
httppost.setEntity(reqEntity);
HttpResponse response = client.execute(httppost);
On server side, there is a
doPost(HttpServletRequest request, HttpServletResponse response)
method which parse the request :
FileItemFactory factory = new DiskFileItemFactory(204800, new File(
uploadDirectory));
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
List<FileItem> items = fileUpload.parseRequest(request);
Iterator<FileItem> itemIterator = items.iterator();
while (itemIterator.hasNext()) {
FileItem item = itemIterator.next();
....
It works fine but the problem is that my FileItem's Content-type is null and I have a NullPointerException later. However when I do bin.getContentType() on client side I get "text/xml".
Does someone know when this Content type is lost and how to fix that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用了错误的模式。在 BROWSER_COMPATIBLE 模式下,内容类型不会发送到服务器。您需要使用 STRICT 模式发送 content_type。
但是,STRICT 可能不适合您,因为某些 Web 服务器不喜欢它。
FileBody 的默认内容类型是 application/octet-stream。你可以这样改,
You are using the wrong mode. In BROWSER_COMPATIBLE mode, the content-type is not sent to server. You need to use STRICT mode to send content_type.
However, STRICT may not work for you because some web servers don't like it.
The default content-type for FileBody is application/octet-stream. You can change it like this,