我正在使用Camel servlet组件来接收xml文档,现在我还需要接收文件(jpeg,gifs等)。以下是我的客户端应用程序发送文件的方式:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class HttpClientUploadHelper {
public boolean upload(final File file, final String url) {
boolean wasSent = false ;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart(file.getName(), new FileBody(file));
post.setEntity(entity);
try {
HttpResponse response = client.execute(post);
wasSent = response.getStatusLine().getStatusCode()==200;
} catch (Exception e) {
}
return wasSent;
}
}
我的Camel处理器然后以这种方式提取HttpServletRequest:
HttpServletRequest req = exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST, HttpServletRequest.class);
然后我有这个方法来最终解析并保存文件:
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils
... class declaration, body, etc...
void parseAndSaveFile(final HttpServletRequest req) throws Exception {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
FileItemIterator receivedFiles = upload.getItemIterator(req);
while (receivedFiles.hasNext()) {
FileItemStream file = receivedFiles.next();
if (file.isFormField()) {
System.out.println("WTF?");
} else {
String fileName = file.getName();
File uploadedFile = new File("/home/myuser/" + fileName);
FileOutputStream out = new FileOutputStream(uploadedFile);
IOUtils.copy(file.openStream(), out);
}
}
}
当我在Camel中使用上面的代码时,isMultipart标志是“true”但是receiveFiles迭代器不包含任何元素。当我在另一个只使用普通servlet的项目中使用上面的代码时,代码可以工作。在这两种方式中,我都使用jetty作为Web容器。
那么有没有其他方法可以提取文件名及其在我的驼色处理器中的内容?
谢谢!
答案 0 :(得分:0)
由于您正在使用Jetty,您是否考虑使用包含的MultipartFilter而不是FileUpload项目?超级干净,易于使用。
来自javadoc:
“此类解码由使用文件输入项的HTML表单发送的multipart / form-data流。发送的任何文件都存储到临时文件中,File对象作为属性添加到请求中。所有其他值通过普通的getParameter API提供,并在将字节转换为字符串时遵循setCharacterEncoding机制。“
答案 1 :(得分:0)
这有帮助吗?
public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); Set names = in.getAttachmentNames(); for(String n: names) { System.out.println("attachment "+n); DataHandler h = in.getAttachment(n); if(h!=null) { try { Object o = h.getContent(); System.out.println(o); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if(!names.isEmpty()) return; }