如果我像这样将文件上传到我的 servlet:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.tumblr.com/api/write");
try
{
MultipartEntity entity = new MultipartEntity();
entity.addPart("type", new StringBody("photo"));
entity.addPart("data", new FileBody(image));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
}
catch (ClientProtocolException e) {}
catch (IOException e) {}
如何在 servlet 中检索内容?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
request.???
}
- 我使用 Google App Server 作为我的 Servlet API
最佳答案
如果您的 Servlet 容器或服务器或引擎的版本<3.0(如 2.5 或更早版本),您可能需要利用第三方库 Apache Commons FileUpload .尽管该文件暗示了对上传文件的使用,但它也有效地处理了来自 POST 方法的上传发布数据,就像它解释的那样 here .
从 3.0 版开始,Servlet API 提供了一些调用来处理发布的数据,这些调用是在 POST 请求中发送的。唯一的要求是实体内容的 MIME 类型编码为“multipart/form-data”。
然后您可以使用以下任一方式检索内容的每个“部分”:
getPart(String partName) :其中“partName”是您的多内容实体的一部分的名称。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String partName = "type"; // or "data" Part part = request.getPart(partName); // read your StringBody type BufferedReader reader = new BufferedReader( new InputStreamReader(part.getInputStream())); String line =""; while((line=reader.readLine())!=null) { // do Something with a line System.out.println(line); } // or with a binary Data partName="data"; part = request.getPart(partName); // read your FileBody data InputStream is = part.getInputStream(); // do Something with you byte data is.read(); // is.read(b); // .. }
它实现与 getPart(partName) 相同的结果,而这里的给定数据是已发送数据的所有部分的集合。要检索此集合的部分的每个部分,只需对集合使用线程安全迭代:
Iterator<Part> iterator = request.getParts().iterator();
Part parts = null;
while (iterator.hasNext()) {
parts = (Part) iterator.next();
//rest of the code block removed
}
}
因为 getPart()/getParts() 只能从 Servlet 3.0 版本开始使用,您将确保使用支持的 Servlet 容器和/或升级您当前的 Servlet 容器。一些支持 3.0 的服务器或 Servlet 容器:
关于java - 如何使用 MultipartEntity 在 servlet 中获取实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10633888/