GWT 实现文件上传和下载

时间:2024-06-07 18:34:02

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

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

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

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

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

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

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 加入

  1. <servlet>
  2. <servlet-name>uploadServlet</servlet-name>
  3. <servlet-class>sample.server.FileUploadServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>uploadServlet</servlet-name>
  7. <url-pattern>/login/fileupload</url-pattern>
  8. </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中代码:

  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. }

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 有了之前的经验相信大家应该找到点头绪了吧? 代码:

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

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是一样的,注意别拼错字母了呀!!!!