GWT 实现文件上传和下载
首先下载两个包 commons-fileupload-?.jar和commons-io-?.jar 将他们配置到你的项目中
先把它们放在 "项目名/war/WEB-INF/lib" 中,之后直接在 properties 中加入到项目中(没配置过可以去网上查eclipse配置jar的方法,很简单的)
之后就开始啦,client 端代码:
- 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());
- }
- });
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
- 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();
- }
- }
- }
- }
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 加入
- <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>
<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中代码:
- 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 );
- }
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 有了之前的经验相信大家应该找到点头绪了吧? 代码:
- 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();
- }
- }
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是一样的,注意别拼错字母了呀!!!!
GWT 实现文件上传和下载的更多相关文章
- java web学习总结(二十四) -------------------Servlet文件上传和下载的实现
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- (转载)JavaWeb学习总结(五十)——文件上传和下载
源地址:http://www.cnblogs.com/xdp-gacl/p/4200090.html 在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传 ...
- JavaWeb学习总结,文件上传和下载
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- java文件上传和下载
简介 文件上传和下载是java web中常见的操作,文件上传主要是将文件通过IO流传放到服务器的某一个特定的文件夹下,而文件下载则是与文件上传相反,将文件从服务器的特定的文件夹下的文件通过IO流下载到 ...
- 使用jsp/servlet简单实现文件上传与下载
使用JSP/Servlet简单实现文件上传与下载 通过学习黑马jsp教学视频,我学会了使用jsp与servlet简单地实现web的文件的上传与下载,首先感谢黑马.好了,下面来简单了解如何通过使用 ...
- JavaWeb学习总结(五十)——文件上传和下载
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- 文件上传和下载(可批量上传)——Spring(三)
在文件上传和下载(可批量上传)——Spring(二)的基础上,发现了文件下载时,只有在Chrome浏览器下文件名正常显示,还有发布到服务器后,不能上传到指定的文件夹目录,如上传20160310.txt ...
- 文件上传和下载(可批量上传)——Spring(二)
针对SpringMVC的文件上传和下载.下载用之前“文件上传和下载——基础(一)”的依然可以,但是上传功能要修改,这是因为springMVC 都为我们封装好成自己的文件对象了,转换的过程就在我们所配置 ...
- Struts2 之 实现文件上传和下载
Struts2 之 实现文件上传和下载 必须要引入的jar commons-fileupload-1.3.1.jar commons-io-2.2.jar 01.文件上传需要分别在struts.xm ...
随机推荐
- 解决cocos2d 热更是连不上https服务器
最近苹果宣布所有上架应用都要用https,我们后端走的是同一个函数,导致Android也要连接https. 百度了下,网上说客户端不需要做什么特殊处理,因为cocos本身是支持https的.但是服务端 ...
- [python]filter
- nvarchar类型自动增长
,Col AS 'XH' + RIGHT('0000' + RTRIM(ID),4)
- javascript之事件
客户端javascript程序采用了异步事件驱动编程模型. 相关事件的几个概念: 事件类型(event type):用来说明发生什么类型事件的字符串: 事件目标(event target):发生事件的 ...
- 打开网页自动弹出qq客户端
新建js后调用即可,打开网站自动弹出qq对话框,若qq为关闭状态则启动qq,之后弹出对话框. document.write("<iframe src='tencent://messag ...
- JavaScript学习代码整理(二)--函数
//JavaScript函数 //简单的求和函数 function sum(a,b) { return a + b; } //函数可以存储在变量中,也可以通过变量调用函数 x = sum(a,b); ...
- leetcode面试准备:Divide Two Integers
leetcode面试准备:Divide Two Integers 1 题目 Divide two integers without using multiplication, division and ...
- SFTP文件上传与下载
SFTP是对ftp进行加密的一种文件协议. 首先是先引入:jsch-0.1.42-sources.jar与jsch-0.1.42.jar包 SFTP文件上传与下载. import java.io.Fi ...
- Android textAppearance的属性设置及TextView属性详解
textAppearance的属性设置 android:textAppearance="?android:attr/textAppearanceSmall" android:tex ...
- 一张图看懂开源许可协议,开源许可证GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
一张图看懂开源许可协议,开源许可证GPL.BSD.MIT.Mozilla.Apache和LGPL的区别 首先借用有心人士的一张相当直观清晰的图来划分各种协议:开源许可证GPL.BSD.MIT.Mozi ...