我会使用gwtupload因为它的简单性。
如果要上传多个文件,请在客户端使用 Multiuploader:
public void onModuleLoad() {
MultiUploader uploader = new MultiUploader();
RootPanel.get().add(uploader);
uploader.addOnFinishUploadHandler(new IUploader.OnFinishUploaderHandler() {
public void onFinish(IUploader uploader) {
if (uploader.getStatus() == Status.SUCCESS) {
UploadedInfo info = uploader.getServerInfo();
System.out.println("File name " + info.name);
System.out.println("File content-type " + info.ctype);
System.out.println("File size " + info.size);
}
}
});
}
在服务器端,只需覆盖UploadAction
库提供的 servlet。
编辑:注意该方法接收一个列表FileItem
,每个 FileItem 是上传文件的临时信息和内容,但不是真正的 java File
。在这里,您可以将业务代码用于创建自己的dirs
结构、处理它们,甚至将它们作为 blob 字段存储在 ddbb 中。在这种情况下,我们将获取所有文件并将它们存储在 temp 文件夹中(请注意,此文件夹在 linux、windows 等中是不同的)。
public class SampleUploadServlet extends UploadAction {
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
String response = "";
for (FileItem item : sessionFiles) {
if ( ! item.isFormField()) {
try {
File file = File.createTempFile("upload-", ".bin");
item.write(file);
/// Send a customized message to the client.
response += file.getAbsolutePath() + "\n";
} catch (Exception e) {
throw new UploadActionException(e);
}
}
}
/// Remove files from session because we have a copy of them
removeSessionFileItems(request);
/// Send your customized message to the client.
return response;
}
}
如果您的 servlet 已经处理多部分请求,您可以使用 GWT 中的标准方式 uisngFileUpload
和FormPanel
,尽管您会错过进度条、文件选择器样式等。
// Add a form-panel to your document
final FormPanel form = new FormPanel();
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
form.setAction("your_upload_servlet_url");
RootPanel.get().add(form);
// Add a file-upload to your form
FileUpload fu = new FileUpload();
form.add(fu);
// submit your form when the user selects a file
fu.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent event) {
form.submit();
}
});