使用Servlet将图像上载到GWT项目中的服务器
我正在开发一个GWT应用程序,其中包括它的其他功能,允许用户上传图像文件并将其存储在服务器上。 到目前为止,我就是这么做的 SERVLET使用Servlet将图像上载到GWT项目中的服务器,gwt,servlets,file-upload,Gwt,Servlets,File Upload,我正在开发一个GWT应用程序,其中包括它的其他功能,允许用户上传图像文件并将其存储在服务器上。 到目前为止,我就是这么做的 SERVLET public class ImageUploadService extends HttpServlet { private static final int MAX_FILE_SIZE = 1 * 1024 * 1024; public void doPost(HttpServletRequest request, HttpServletResponse
public class ImageUploadService extends HttpServlet {
private static final int MAX_FILE_SIZE = 1 * 1024 * 1024;
public void doPost(HttpServletRequest request, HttpServletResponse response) {
wlog("INFO: è partita la servlet");
if (!ServletFileUpload.isMultipartContent(request))
wlog("ERR: non è multipart!");
ServletFileUpload fileUpld = new ServletFileUpload();
try {
wlog("INFO: itero file");
FileItemIterator fileIt = fileUpld.getItemIterator(request);
while (fileIt.hasNext()) {
wlog("INFO: trovato file");
FileItemStream fileStream = fileIt.next();
BufferedInputStream in = new BufferedInputStream(
fileStream.openStream(), 4096);
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream("immagineSegnalazione.jpg"));
byte[] buf = new byte[MAX_FILE_SIZE];
int byteRead;
while ((byteRead = in.read(buf, 0, MAX_FILE_SIZE)) >= 0) {
out.write(buf, 0, byteRead);
}
in.close();
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void wlog(String s) {
System.out.println("UPLOAD SERVLET " + s);
}
}
客户端上的模块
[...]
PopupPanel inserisciSegnalazionePopup = new PopupPanel();
final FormPanel uploadForm = new FormPanel();
uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadForm.setMethod(FormPanel.METHOD_POST);
inserisciSegnalazionePopup.setAutoHideEnabled(true);
VerticalPanel holder = new VerticalPanel();
holder.add(new Label("se puoi, allega una foto della segnalazione"));
final FileUpload fu = new FileUpload();
uploadForm.add(fu);
holder.add(uploadForm);
uploadForm.setAction(GWT.getModuleBaseURL() + "imageUpload");
Button inviaBtn = new Button("INVIA SEGNALAZIONE");
inviaBtn.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
// TODO check file is image and size and other stuff
uploadForm.submit();
}
});
holder.add(inviaBtn);
[...]
…另外,我已经正确地对web.xml进行了所需的更改
Servlet被正确调用,方法doPost()启动,但FileItemIterator始终为空,就好像根本没有文件一样。。
有人能猜出怎么了吗?我真的看不出哪里出了错
提前谢谢你我猜在你使用请求之前,请求已经被解析了。试着看一看,结果是,似乎是几乎相同的问题 Sarajog你试过这个吗
Iterator<FileItem> iterator = upload.parseRequest(request).iterator();
Iterator Iterator=upload.parseRequest(request.Iterator();
解决方案是。。。
只需将.setName()添加到FileUpload小部件我遵循了Sarajog的建议和你的建议,但行为完全相同..在我显示的部分代码之前从未解析请求..我尝试按照你提供给我的链接中的建议更改代码,但迭代器仍然为空。。