【问题标题】:smartgwt spring servlet and uploading filessmartgwt spring servlet和上传文件
【发布时间】:2014-07-30 10:29:33
【问题描述】:

我以前在这里看到过这个问题,但没有一个解决方案适合我。 我有一个带有 Spring MVC 的 SmartGWT 应用程序。这一切都很好,我有工作的 RESTful 网络服务。

我有一个表单,不仅可以上传文件,还可以上传一些元数据。 此表单有一个关联的 DataSource:

private final String DEFAULT_FILE_UPLOAD_SERVICE_PATH = "upload";
private final String TARGET = "uploadTarget";

 public FileUploadForm()
{
    setEncoding(Encoding.MULTIPART);
    setMethod(FormMethod.POST);

    setAutoFetchData(false);
    setDataSource(fileUploadDS);

    setTitleOrientation(TitleOrientation.TOP);
    setNumCols(1);
    setColWidths("*");

    uploadFileIdItem.setRequired(true);
    uploadFileIdItem.setDefaultValue(0);
    uploadFileIdItem.setVisible(false);
    uploadFileIdItem.setShowTitle(false);

    // ==========================================================================

    fileUploadTypeSelectItem.setShowTitle(false);
    fileUploadTypeSelectItem.setName(Constants.FILE_UPLOAD_UPLOADTYPE);
    fileUploadTypeSelectItem.setPickListWidth(TEXT_SIZE);
    fileUploadTypeSelectItem.setTitle(Constants.TITLE_FILE_UPLOAD_UPLOADTYPE);
    fileUploadTypeSelectItem.setOptionDataSource(fileUploadTypeDS);
    fileUploadTypeSelectItem.setRequired(true);
    fileUploadTypeSelectItem.setDisplayField(Constants.FILE_UPLOAD_UPLOADTYPE_NAME);
    fileUploadTypeSelectItem.setValueField(Constants.FILE_UPLOAD_UPLOADTYPE_ID);
    fileUploadTypeSelectItem.setDataPath("fileUploadType/fileUploadTypeId");

    // ==========================================================================

    setAction(GWT.getHostPageBaseURL() + "rest/" + DEFAULT_FILE_UPLOAD_SERVICE_PATH);

    ButtonItem uploadButton = new ButtonItem("Upload");

    uploadButton.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler()
    {
        @Override
        public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event)
        {
            submitForm();
        }
    });

    FileItem uploadItem = new FileItem(Constants.FILENAME);
    uploadItem.setTitle(Constants.FILENAME);

    setFields(uploadFileIdItem, fileUploadTypeSelectItem, uploadItem, uploadButton);
}

所以,我不知道是否需要使用: setAction(GWT.getHostPageBaseURL() + "rest/" + DEFAULT_FILE_UPLOAD_SERVICE_PATH); 要么 setAction(GWT.getHostPageBaseURL() + DEFAULT_FILE_UPLOAD_SERVICE_PATH); 要么 setAction(GWT.getHostPageBaseURL() + DEFAULT_FILE_UPLOAD_SERVICE_PATH);

这些似乎都不起作用,我提交数据以上传文件名,并且不断收到 HTTP 404 错误。

我没有在 web.xml 文件中为 servlet 定义任何额外的特殊内容。 相反,springmvc-servlet 包含:

<context:component-scan base-package="com.myself.products.app.server.controller" />

而servlet实际上是这样定义的:

@SuppressWarnings("serial")
@Controller
@RequestMapping("/upload")
public class FileUploadServlet extends HttpServlet
{
    private final Logger logger = LoggerFactory.getLogger(FileUploadServlet.class);

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    this.process(request, response);
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    this.process(request, response);
}

private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    // check that we have a file upload request
    if (ServletFileUpload.isMultipartContent(request))
    {
        processFiles(request, response);
    }
}

private File tmpDir;
private static final String DESTINATION_DIR_PATH = "/files/upload";
private File destinationDir;

public void init(ServletConfig config) throws ServletException
{
    super.init(config);

    tmpDir = new File(((File) getServletContext().getAttribute("javax.servlet.context.tempdir")).toString());

    if (!tmpDir.isDirectory())
    {
        throw new ServletException(tmpDir.toString() + " is not a directory");
    }

    logger.debug("tmpDir: " + tmpDir.toString());

    String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
    destinationDir = new File(realPath);

    if (!destinationDir.isDirectory())
    {
        throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
    }
}

private void processFiles(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    IOException
{

    // create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // set the size threshold, above which content will be stored on disk
    factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB

    // set the temporary directory (this is where files that exceed the threshold will be stored)
    factory.setRepository(tmpDir);

    // create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    try
    {
        // parse the request
        List<?> items = upload.parseRequest(request);

        // process the uploaded items
        Iterator<?> itr = items.iterator();

        while (itr.hasNext())
        {
            FileItem item = (FileItem) itr.next();

            // write the uploaded file to the application's file staging area
            File file = new File(destinationDir, item.getName());
            item.write(file);
        }

    }
    catch (FileUploadException e)
    {
        logger.error("Error encountered while parsing the request", e);
    }
    catch (Exception e)
    {
        logger.error("Error encountered while uploading file", e);
    }
}

您之前已经在本网站以及其他几个网站上看到过此代码。

如果可能,我想提交文件和数据,但如果没有,那我如何提交表单,然后提交元数据?

任何帮助将不胜感激。

【问题讨论】:

    标签: rest spring-mvc servlets smartgwt


    【解决方案1】:

    我建议您将保存元数据与上传文件分开保存,并有两种形式。这就是我正在做的,它对我有用:

    uploadForm.setAction(GWT.getHostPageBaseURL() + "importServiceName");
    uploadForm.setEncoding(Encoding.MULTIPART);
    uploadForm.setTarget(TARGET);
    uploadForm.setMethod(FormMethod.POST);
    fileItem = new UploadItem("file");
    fileItem.setTitle("File");
    fileItem.setWidth(300);
    NamedFrame frame = new NamedFrame(TARGET);
    frame.setWidth("1");
    frame.setHeight("1");
    frame.setVisible(false);
    uploadForm.setItems(fileItem);
    

    我正在使用 NamedFrame 来获取 gwt 代码中的 servlet 响应,但这是另一回事。我在 web.xml 中手动定义 servler

    【讨论】:

      【解决方案2】:

      简单文件上传 GWT 示例:

      可在此处获得: http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FileUpload.html

      要随请求一起发送元数据,需要将隐藏字段设置为面板:

      import com.google.gwt.user.client.ui.Hidden;
      
      Hidden hidden = new Hidden();
      hidden.setName("json");
      hidden.setVisible(false); 
      
      hidden.setValue("simpleMetadata:testData");
      panel.add(hidden);
      

      【讨论】:

      • 是的,我很确定这就是我最终解决问题的方法。我只需要更新答案,但这基本上就是我所做的。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2019-01-02
      • 2013-06-27
      • 1970-01-01
      • 2012-02-10
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      相关资源
      最近更新 更多