博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
GWT 实现文件上传和下载
阅读量:6429 次
发布时间:2019-06-23

本文共 10064 字,大约阅读时间需要 33 分钟。

首先下载两个包 commons-fileupload-?.jar和commons-io-?.jar  将他们配置到你的项目中

先把它们放在 "项目名/war/WEB-INF/lib" 中,之后直接在 properties 中加入到项目中(没配置过可以去网上查eclipse配置jar的方法,很简单的)

 

之后就开始啦,client 端代码:

 

[java]
  1. final FileUpload fileUpload = new FileUpload();  
  2. final FormPanel formpanel = new FormPanel();  
  3.   
  4. fileUpload.setName("uploadFormElement");  
  5.         formpanel.setEncoding( FormPanel.ENCODING_MULTIPART );  
  6.         formpanel.setMethod( FormPanel.METHOD_POST );  
  7.         formpanel.setAction( GWT.getModuleBaseURL() + "fileupload" );  
  8.         formpanel.setWidget( fileUpload );  
  9.           
  10.         uploadbutton.addClickHandler( new ClickHandler() {  
  11.             public void onClick( ClickEvent sender ) {  
  12.                 formpanel.submit();  
  13.             }  
  14.         });  
  15.         formpanel.addSubmitHandler( new SubmitHandler() {  
  16.             public void onSubmit(SubmitEvent event) {  
  17.                 if( fileUpload.getFilename().length() == 0 ) {  
  18.                     Window.alert( "you must select a file" );  
  19.                 }  
  20.                   
  21.             }  
  22.         });  
  23.         formpanel.addSubmitCompleteHandler( new SubmitCompleteHandler() {  
  24.             public void onSubmitComplete(SubmitCompleteEvent event) {  
  25.                 //兼容linux文件分隔符?  
  26.                 String selected = fileUpload.getFilename().replaceAll("/""//");  
  27.                 selected = selected.substring( selected.lastIndexOf("//")+1);  
  28.                                 Window.alert( "upload complete"+ event.getResults());  
  29.             }  
  30.         });  

final FileUpload fileUpload = new FileUpload(); final FormPanel formpanel = new FormPanel(); fileUpload.setName("uploadFormElement"); formpanel.setEncoding( FormPanel.ENCODING_MULTIPART ); formpanel.setMethod( FormPanel.METHOD_POST ); formpanel.setAction( GWT.getModuleBaseURL() + "fileupload" ); formpanel.setWidget( fileUpload ); uploadbutton.addClickHandler( new ClickHandler() { public void onClick( ClickEvent sender ) { formpanel.submit(); } }); formpanel.addSubmitHandler( new SubmitHandler() { public void onSubmit(SubmitEvent event) { if( fileUpload.getFilename().length() == 0 ) { Window.alert( "you must select a file" ); } } }); formpanel.addSubmitCompleteHandler( new SubmitCompleteHandler() { public void onSubmitComplete(SubmitCompleteEvent event) { //兼容linux文件分隔符? String selected = fileUpload.getFilename().replaceAll("/", "//"); selected = selected.substring( selected.lastIndexOf("//")+1); Window.alert( "upload complete"+ event.getResults()); } });

 

之后再server中添加服务 :FileUploadServlet.java

 

[java]
  1. package sample.server;  
  2.   
  3.   
  4. import java.io.File;  
  5. import java.io.IOException;  
  6. import java.util.Iterator;  
  7. import java.util.List;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12. import org.apache.commons.fileupload.FileItem;  
  13. import org.apache.commons.fileupload.FileItemFactory;  
  14. import org.apache.commons.fileupload.FileUploadException;  
  15. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  16. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  17.   
  18. public class FileUploadServlet extends HttpServlet {  
  19.     private static final long serialVersionUID = 1L;  
  20.       
  21.     @Override  
  22.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  23.         throws ServletException, IOException {  
  24.     // TODO Auto-generated method stub  
  25.       
  26.         response.setContentType("text/html");  
  27.         response.setCharacterEncoding("utf-8");   
  28.         FileItemFactory factory = new DiskFileItemFactory();  
  29.         ServletFileUpload upload = new ServletFileUpload(factory);       
  30.       
  31.         List items = null;       
  32.   
  33.         try {      
  34.             items = upload.parseRequest(request);       
  35.         }  
  36.         catch (FileUploadException ex) {       
  37.             ex.printStackTrace();       
  38.         }      
  39.       
  40.         Iterator iter = items.iterator();       
  41.       
  42.         while (iter.hasNext()) {       
  43.             FileItem item = (FileItem) iter.next();       
  44.        
  45.             String savePath = getServletContext().getRealPath("/uploads");  
  46.                               
  47.             String filename = item.getName();     
  48.      
  49.             String filename2 = filename.replaceAll("/""//");  
  50.             int pos = filename.lastIndexOf( "//") + 1;  
  51.      
  52.             File file = new File(savePath,filename.substring( pos ) );   
  53.            
  54.             try {  
  55.                 item.write(file);  
  56.             }   
  57.             catch (Exception e) {     
  58.                 e.printStackTrace();  
  59.             }      
  60.         }       
  61.     }      
  62. }  

package sample.server; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException ex) { ex.printStackTrace(); } Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String savePath = getServletContext().getRealPath("/uploads"); String filename = item.getName(); String filename2 = filename.replaceAll("/", "//"); int pos = filename.lastIndexOf( "//") + 1; File file = new File(savePath,filename.substring( pos ) ); try { item.write(file); } catch (Exception e) { e.printStackTrace(); } } } }

 

 

最后 最重要的一步!! 打开web.xml 加入

 

[xhtml]
  1. <servlet>  
  2.     <servlet-name>uploadServlet</servlet-name>  
  3.     <servlet-class>sample.server.FileUploadServlet</servlet-class>  
  4.   </servlet>  
  5.     
  6.   <servlet-mapping>  
  7.     <servlet-name>uploadServlet</servlet-name>  
  8.     <url-pattern>/login/fileupload</url-pattern>  
  9.   </servlet-mapping>  

<servlet> <servlet-name>uploadServlet</servlet-name> <servlet-class>sample.server.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>uploadServlet</servlet-name> <url-pattern>/login/fileupload</url-pattern> </servlet-mapping>

 

两个servlet-name 相同即可 而servlet-class对应之前添加的服务,url-pattern对应 client端中的

formpanel.setAction( GWT.getModuleBaseURL() + "fileupload" );

打开 xxx.gwt.xml 加入 :<servlet class="sample.server.FileUploadServlet" path="/fileupload" />

class 和 path也是对应的,别搞错啦,不然会悲剧的

 

好吧可以运行试试了,下面看download

 

download简单一点点,client中代码:

 

[java]
  1. void download( String filename ) {  
  2.         if( RootPanel.get("downloadiframe") != null ) {  
  3.             Widget widgetFrame = (Widget)RootPanel.get("downloadiframe");  
  4.             widgetFrame.removeFromParent();  
  5.         }   
  6.         Frame frame = new Frame( GWT.getModuleBaseURL() + "filedownload" + "?id=downloadiframe"+  
  7.                 "&filename=" + filename );  
  8.         frame.setVisible( false );  
  9.         frame.setSize( "0px""0px" );  
  10.         RootPanel.get().add( frame );  
  11.           
  12.     }  

void download( String filename ) { if( RootPanel.get("downloadiframe") != null ) { Widget widgetFrame = (Widget)RootPanel.get("downloadiframe"); widgetFrame.removeFromParent(); } Frame frame = new Frame( GWT.getModuleBaseURL() + "filedownload" + "?id=downloadiframe"+ "&filename=" + filename ); frame.setVisible( false ); frame.setSize( "0px", "0px" ); RootPanel.get().add( frame ); }

 

 

同样新建一个 DownloadServlet.java 有了之前的经验相信大家应该找到点头绪了吧? 代码:

 

[java]
  1. package sample.server;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.IOException;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletOutputStream;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import com.google.gwt.core.client.GWT;  
  15. import com.google.gwt.user.client.ui.Frame;  
  16.   
  17. public class DownloadServlet extends HttpServlet {  
  18.     private static final long serialVersionUID = 1L;  
  19.   
  20.     protected void doGet( HttpServletRequest req, HttpServletResponse resp )  
  21.         throws ServletException, IOException  
  22.     {  
  23.         //此函数对应之前的 Frame frame =   
  24.         //new Frame( GWT.getModuleBaseURL() + "filedownload" + "?id=downloadiframe"+"&filename=" + filename );  
  25.         //传文件名那个简单啊  
  26.         String filename = req.getParameter("filename");  
  27.           
  28.         //这边你要自己决定从哪下载的文件!! 我是把上传路径直接给他了  
  29.         //这里说下。。我先前没自己创建 uploads 结果十分悲剧  
  30.         //记得在 war 路径下创建 !!  
  31.         String filepath = req.getRealPath("/uploads");  
  32.         File file = new File( filepath+"/"+filename );  
  33.   
  34.         //下面代码从网上拉的,直接抄就行了  
  35.         FileInputStream fis = new FileInputStream(file);  
  36.         resp.addHeader("Content-Disposition","attachment; filename=" + filename );  
  37.   
  38.         ServletOutputStream out = resp.getOutputStream();  
  39.         resp.setBufferSize(32768);  
  40.         int bufSize = resp.getBufferSize();  
  41.         byte[] buffer = new byte[bufSize];  
  42.         BufferedInputStream bis = new BufferedInputStream(fis,bufSize);  
  43.   
  44.         int bytes;  
  45.         while ((bytes = bis.read(buffer, 0, bufSize)) >= 0)  
  46.             out.write(buffer, 0, bytes);  
  47.         bis.close();  
  48.         fis.close();  
  49.         out.flush();  
  50.         out.close();  
  51.     }  
  52. }  

package sample.server; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.Frame; public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { //此函数对应之前的 Frame frame = //new Frame( GWT.getModuleBaseURL() + "filedownload" + "?id=downloadiframe"+"&filename=" + filename ); //传文件名那个简单啊 String filename = req.getParameter("filename"); //这边你要自己决定从哪下载的文件!! 我是把上传路径直接给他了 //这里说下。。我先前没自己创建 uploads 结果十分悲剧 //记得在 war 路径下创建 !! String filepath = req.getRealPath("/uploads"); File file = new File( filepath+"/"+filename ); //下面代码从网上拉的,直接抄就行了 FileInputStream fis = new FileInputStream(file); resp.addHeader("Content-Disposition","attachment; filename=" + filename ); ServletOutputStream out = resp.getOutputStream(); resp.setBufferSize(32768); int bufSize = resp.getBufferSize(); byte[] buffer = new byte[bufSize]; BufferedInputStream bis = new BufferedInputStream(fis,bufSize); int bytes; while ((bytes = bis.read(buffer, 0, bufSize)) >= 0) out.write(buffer, 0, bytes); bis.close(); fis.close(); out.flush(); out.close(); } }

 

 

 

配置两个xml和upload是一样的,注意别拼错字母了呀!!!!

转载地址:http://ogjga.baihongyu.com/

你可能感兴趣的文章
【linux】浅谈Linux下的 find 指令
查看>>
CentOS 7 使用kubeadm 部署 Kubernetes
查看>>
我的友情链接
查看>>
透视美国大数据爆发全景
查看>>
java学习第一天1.2
查看>>
清空输入缓冲区的方法
查看>>
Yii2 项目优化小贴士
查看>>
UIScrollView的判断位置的属性如下:
查看>>
Applicatin Loader上传app步骤记录
查看>>
两种方法修改table表的内容
查看>>
张小龙莫慌 马化腾莫急 你们要好好的 微信还有时间
查看>>
一些常用软件静默安装参数(nsis,msi,InstallShield ,Inno)
查看>>
部署mimic版本的Ceph分布式存储系统
查看>>
Java缓冲流细节
查看>>
IOS中复制对象的用法及深拷贝和浅拷贝详解
查看>>
lfs
查看>>
Eclipse内存不够解决办法
查看>>
关于tbody js取法兼容。
查看>>
[CC]点云密度计算
查看>>
CATransition 动画处理视图切换
查看>>