[英]in GWT, How to build a system that allow users to upload their image into a folder in Webserver?
在Java Desktop
應用程序中,我們可以允許用戶將文件上傳到WebServer的文件夾中,如下所示
File rootDir = new File( "/home/bala/temp" ) ;
if( FileUpload.isMultipartContent( request ) ) {
DiskFileUpload fileUpload = new DiskFileUpload() ;
Iterator iterator = fileUpload.parseRequest( request ).iterator() ;
while( iterator.hasNext() ) {
FileItem fileItem = ( FileItem ) iterator.next() ;
File file = new File( rootDir , fileItem.getName() ) ;
fileItem.write( file ) ; }
}
else { throw new Exception( "Invalid request " ) ; }
但是我們如何在Gwt或GWTP中做到這一點 ? Gwt是否包含支持此的任何類?
由於其簡單性,我將使用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
結構,對其進行處理,甚至將其存儲為ddbb中的blob字段。 在這種情況下,我們將獲取所有文件並將它們存儲在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 FormPanel
FileUpload
和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();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.