1

我正在使用这个库:http ://www.moxiegroup.com/moxieapps/gwt-uploader/ ,在我的 Web 应用程序中上传文件。我按照此处解释的步骤操作:http ://www.moxiegroup.com/moxieapps/gwt-uploader/userguide.jsp ,并在他们的展示中使用第一个示例:http ://www.moxiegroup.com/moxieapps/gwt- uploader/showcase/index.jsp,我用我的servlet信息修改了方法中的参数,Upload.setUploadURL()看起来一切正常。服务器日志甚至说文件已成功上传。我的问题是我找不到它(文件)。我应该在哪里寻找它或者我可以在哪里设置文件应该上传的路径?

这是客户端代码:

包org.moxieapps.gwt.uploader.showcase.client;

import com.google.gwt.core.client.EntryPoint;  
import com.google.gwt.i18n.client.NumberFormat;  
import com.google.gwt.user.client.Window;  
import com.google.gwt.user.client.ui.HorizontalPanel;  
import com.google.gwt.user.client.ui.Label;  
import com.google.gwt.user.client.ui.RootPanel;  
import com.google.gwt.user.client.ui.VerticalPanel;  
import org.moxieapps.gwt.uploader.client.Uploader;  
import org.moxieapps.gwt.uploader.client.events.*;  

/** 
 * Simple Text Link and Progress text label example of GWT Uploader 
 */  
public class TextButtonAndProgressText implements EntryPoint {  

    private Label progressLabel;  
    private Uploader uploader;  

    public void onModuleLoad() {  
        progressLabel = new Label();  
        progressLabel.setStyleName("progressLabel");  

        uploader = new Uploader();  
        uploader.setUploadURL("/DevNullUploadServlet")  
            .setButtonText("<span class=\"buttonText\">Click to Upload</span>")  
            .setButtonTextStyle(".buttonText {font-family: Arial, sans-serif; font-size: 14px; color: #BB4B44}")  
            .setFileSizeLimit("50 MB")  
            .setButtonWidth(150)  
            .setButtonHeight(22)  
            .setButtonCursor(Uploader.Cursor.HAND)  
            .setButtonAction(Uploader.ButtonAction.SELECT_FILE)  
            .setUploadProgressHandler(new UploadProgressHandler() {  
                public boolean onUploadProgress(UploadProgressEvent uploadProgressEvent) {  
                    progressLabel.setText(NumberFormat.getPercentFormat().format(  
                        (double)uploadProgressEvent.getBytesComplete() / (double)uploadProgressEvent.getBytesTotal()  
                    ));  
                    return true;  
                }  
            })  
            .setUploadSuccessHandler(new UploadSuccessHandler() {  
                public boolean onUploadSuccess(UploadSuccessEvent uploadSuccessEvent) {  
                    resetText();  
                    StringBuilder sb = new StringBuilder();  
                    sb.append("File ").append(uploadSuccessEvent.getFile().getName())  
                        .append(" (")  
                        .append(NumberFormat.getDecimalFormat().format(uploadSuccessEvent.getFile().getSize() / 1024))  
                        .append(" KB)")  
                        .append(" uploaded successfully at ")  
                        .append(NumberFormat.getDecimalFormat().format(  
                            uploadSuccessEvent.getFile().getAverageSpeed() / 1024  
                        ))  
                        .append(" Kb/second");  
                    progressLabel.setText(sb.toString());  
                    return true;  
                }  
            })  
            .setFileDialogCompleteHandler(new FileDialogCompleteHandler() {  
                public boolean onFileDialogComplete(FileDialogCompleteEvent fileDialogCompleteEvent) {  
                    if (fileDialogCompleteEvent.getTotalFilesInQueue() > 0 && uploader.getStats().getUploadsInProgress() <= 0) {  
                        progressLabel.setText("0%");  
                        uploader.setButtonText("<span class=\"buttonText\">Uploading...</span>");  
                        uploader.startUpload();  
                    }  
                    return true;  
                }  
            })  
            .setFileQueueErrorHandler(new FileQueueErrorHandler() {  
                public boolean onFileQueueError(FileQueueErrorEvent fileQueueErrorEvent) {  
                    resetText();  
                    Window.alert("Upload of file " + fileQueueErrorEvent.getFile().getName() + " failed due to [" +  
                        fileQueueErrorEvent.getErrorCode().toString() + "]: " + fileQueueErrorEvent.getMessage()  
                    );  
                    return true;  
                }  
            })  
            .setUploadErrorHandler(new UploadErrorHandler() {  
                public boolean onUploadError(UploadErrorEvent uploadErrorEvent) {  
                    resetText();  
                    Window.alert("Upload of file " + uploadErrorEvent.getFile().getName() + " failed due to [" +  
                        uploadErrorEvent.getErrorCode().toString() + "]: " + uploadErrorEvent.getMessage()  
                    );  
                    return true;  
                }  
            });  

        VerticalPanel verticalPanel = new VerticalPanel();  
        verticalPanel.add(uploader);  
        verticalPanel.add(progressLabel);  
        verticalPanel.setCellHorizontalAlignment(uploader, HorizontalPanel.ALIGN_LEFT);  
        verticalPanel.setCellHorizontalAlignment(progressLabel, HorizontalPanel.ALIGN_LEFT);  

        //noinspection GwtToHtmlReferences  
        RootPanel.get("TextButtonAndProgressText").add(verticalPanel);  
    }  

    private void resetText() {  
        progressLabel.setText("");  
        uploader.setButtonText("<span class=\"buttonText\">Click to Upload</span>");  
    }  
}  

这是服务器代码:

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileUploadServlet extends HttpServlet {

  private long FILE_SIZE_LIMIT = 20 * 1024 * 1024; // 20 MiB
  private final Logger logger = Logger.getLogger("UploadServlet");

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    try {
      DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
      ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
      fileUpload.setSizeMax(FILE_SIZE_LIMIT);

      List<FileItem> items = fileUpload.parseRequest(req);

      for (FileItem item : items) {
        if (item.isFormField()) {
          logger.log(Level.INFO, "Received form field:");
          logger.log(Level.INFO, "Name: " + item.getFieldName());
          logger.log(Level.INFO, "Value: " + item.getString());
        } else {
          logger.log(Level.INFO, "Received file:");
          logger.log(Level.INFO, "Name: " + item.getName());
          logger.log(Level.INFO, "Size: " + item.getSize());
        }

        if (!item.isFormField()) {
          if (item.getSize() > FILE_SIZE_LIMIT) {
            resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
              "File size exceeds limit");

            return;
          }

          // Typically here you would process the file in some way:
          // InputStream in = item.getInputStream();
          // ...

          if (!item.isInMemory())
            item.delete();
        }
      }
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
      throw new ServletException(e);
    }
  }

}  
4

1 回答 1

3

尽管日志显示文件已成功上传,但您实际上从未将文件保存到本地磁盘。

  for (FileItem item : items) {
    if (item.isFormField()) {
      logger.log(Level.INFO, "Received form field:");
      logger.log(Level.INFO, "Name: " + item.getFieldName());
      logger.log(Level.INFO, "Value: " + item.getString());
    } else {
      logger.log(Level.INFO, "Received file:");
      logger.log(Level.INFO, "Name: " + item.getName());
      logger.log(Level.INFO, "Size: " + item.getSize());
    }

以上是显示记录器能够找到 FileItems 并记录其详细信息的相关代码。

几行之后,有以下注释:

      // Typically here you would process the file in some way:
      // InputStream in = item.getInputStream();
      // ...

这就是我猜测本教程让您决定如何将文件写入磁盘的地方。查看使用 InputStream 将文件写入磁盘,您应该没有问题。上传部分似乎工作正常,您只需要将上传的文件写入磁盘。

编辑: 您使用的 Apache FileUpload 库似乎有一些简单的方法可以尝试将文件写入磁盘。用以下几行替换注释应该有效:

File newFile= new File("C:/path/to/directory");
item.write(newFile);
于 2013-09-10T20:47:36.967 回答