Java GWT 中的基本文件上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1111130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Basic File upload in GWT
提问by Maksim
I'm trying to figure out how to upload one file using GWTs FileUpload widget. I'm using GWT and Google AppEngine with Java but I would like to upload file to my own Linux server. I have the following code already but now I can't figure out how to submit my file to the Google AppServer server and save it to another server:
我想弄清楚如何使用 GWTs FileUpload 小部件上传一个文件。我在 Java 中使用 GWT 和 Google AppEngine,但我想将文件上传到我自己的 Linux 服务器。我已经有了以下代码,但现在我不知道如何将我的文件提交到 Google AppServer 服务器并将其保存到另一台服务器:
public class FileUploader{
private ControlPanel cp;
private FormPanel form = new FormPanel();
private FileUpload fu = new FileUpload();
public FileUploader(ControlPanel cp) {
this.cp = cp;
this.cp.setPrimaryArea(getFileUploaderWidget());
}
@SuppressWarnings("deprecation")
public Widget getFileUploaderWidget() {
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// form.setAction(/* WHAT SHOULD I PUT HERE */);
VerticalPanel holder = new VerticalPanel();
fu.setName("upload");
holder.add(fu);
holder.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.log("You selected: " + fu.getFilename(), null);
form.submit();
}
}));
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event) {
if (!"".equalsIgnoreCase(fu.getFilename())) {
GWT.log("UPLOADING FILE????", null);
// NOW WHAT????
}
else{
event.cancel(); // cancel the event
}
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert(event.getResults());
}
});
form.add(holder);
return form;
}
}
Now, what do I need to do next? What do i need to put in web.xml and how do I write my servlet so i can store file and return url of that object (if possible)
现在,我接下来需要做什么?我需要在 web.xml 中放入什么以及如何编写我的 servlet 以便我可以存储文件并返回该对象的 url(如果可能)
采纳答案by KevMo
Here's the code from my app:
这是我的应用程序中的代码:
1) I created a class to accept http request:
1)我创建了一个类来接受http请求:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10*(1024*1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
}
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
2) Then in my web.xml I've added these lines:
2)然后在我的 web.xml 我添加了这些行:
<servlet>
<servlet-name>fileUploaderServlet</servlet-name>
<servlet-class>com.testapp.server.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUploaderServlet</servlet-name>
<url-pattern>/testapp/fileupload</url-pattern>
</servlet-mapping>
3) And for form.action did this:
3)对于 form.action 这样做:
form.setAction(GWT.getModuleBaseURL()+"fileupload");
回答by KevMo
In GWT, you can post the file to the server using http form methods, and you must use the supplied HttpServlet to accept and save the data as binary blogs in the Appengine BigTable.
在 GWT 中,您可以使用 http 表单方法将文件发布到服务器,并且您必须使用提供的 HttpServlet 来接受数据并将其保存为 Appengine BigTable 中的二进制博客。
Then, you need a second HttpServlet to read the file from bigtable, SET THE MIME TYPE IN THE HTTP HEADER {and caching options}, and then stream the file to the user.
然后,您需要第二个 HttpServlet 从 bigtable 读取文件,在 HTTP 标头中设置 MIME 类型{和缓存选项},然后将文件流式传输给用户。
Although RPC isn't NECESSARILY needed, you must let the client know what the generated fileId is so they can access it {unless you want to let user's supply the id and force them to worry about name overrides... ...ick}. Either you can use rpc to ask for a list of / single id {like "newest file id by user"}, or you can return that id in the body of the UploadServlet's response... but then you must make sure your post target is an in-page iframe, poll to make sure the iframe has a body between the submit event and the actual server response, and then parse and use that id in gwt to create an img or object tag that uses the file.
尽管 RPC 不是必需的,但您必须让客户端知道生成的 fileId 是什么,以便他们可以访问它{除非您想让用户提供 id 并强迫他们担心名称覆盖... ...ick} . 您可以使用 rpc 来请求 / 单个 id 的列表 {like "newest file id by user"},或者您可以在 UploadServlet 的响应正文中返回该 id ...但是您必须确保您的帖子目标是页内 iframe,轮询以确保 iframe 在提交事件和实际服务器响应之间有一个正文,然后解析并在 gwt 中使用该 id 以创建使用该文件的 img 或 object 标记。
The key part is having one servlet for upload, and another to download. Remember, BigTable just stores binary blobs, so you also need your data entity to have a mime/content Type that can be read from the input file {never rely on file extensions!}. Also, there's a 1MB per entity in the BigTable, and a 10MB request limit for free accounts. You may wish to have your data entity contain a list of 1-10 blobs, each of which are a max 1024bytes.
关键部分是让一个 servlet 用于上传,另一个用于下载。请记住,BigTable 只存储二进制 blob,因此您还需要您的数据实体具有可从输入文件中读取的 MIME/内容类型{永远不要依赖文件扩展名!}。此外,BigTable 中每个实体有 1MB 的空间,免费帐户有 10MB 的请求限制。您可能希望您的数据实体包含 1-10 个 blob 的列表,每个 blob 最大为 1024 字节。
Basically, your best bet is to find a working, free copy, like Google File Service, and extend it to learn how the system works.
基本上,最好的办法是找到一个可用的免费副本,例如 Google 文件服务,并对其进行扩展以了解系统的工作原理。
If you wish, I will be posting my own open-source version of file handling, once I finish the gwt control widgets and can consider it all stable enough to be useful to anyone. Email x ATaiyx DOTinfo if you want me to send you a jar of betalicious code.
如果您愿意,我将发布我自己的文件处理的开源版本,一旦我完成了 gwt 控件小部件,并且可以认为它足够稳定以供任何人使用。如果您想让我向您发送一罐恶意代码,请通过电子邮件发送 x ATaiyx DOT信息。
回答by rluba
I would suggest using GWTUploadbecause it's dead simple to use and extend. You can add it to your project in less than 10 minutes and it supports GAE right out of the box (using GWTUpload-GAE). See the examplesfor some common usage scenarios.
我建议使用GWTUpload,因为它的使用和扩展非常简单。您可以在不到 10 分钟的时间内将其添加到您的项目中,并且它开箱即用地支持 GAE(使用 GWTUpload-GAE)。一些常见的使用场景请参见示例。
回答by Jeff Richley
Unless you are already using other frameworks, I'd strongly suggest using plain vanilla GWT and it's native components. If you use other frameworks, you can explode the size of your application greatly.
除非您已经在使用其他框架,否则我强烈建议您使用普通的 GWT 并且它是本机组件。如果你使用其他框架,你的应用程序的大小可能会大大爆炸。
Using the native components can be done in 3 steps:
使用原生组件可以通过 3 个步骤完成:
- Create a file upload servlet
- Modify web.xml
- Make a GWT Upload Form
- 创建文件上传servlet
- 修改 web.xml
- 制作 GWT 上传表单
Interestingly enough, the GWT part is the easiest. You can copy my code at GWT Upload in 3 easy stepsif you'd like. Happy uploading!
有趣的是,GWT 部分是最简单的。如果您愿意,可以通过 3 个简单的步骤在GWT Upload 上复制我的代码。上传快乐!
回答by Suresh Atta
Here you go with a complete GWT fileupload with Progress bar
Here you can DOWNLOADthe source
在这里你可以下载源