簡體   English   中英

jQuery / Ajax和Spring Rest多部分表單提交

[英]JQuery/Ajax & Spring Rest Multi-part form submit

我對JQuery還是很陌生,我正在嘗試進行一些異步的多部分表單上傳。 該表格由幾個數據字段和一個文件類型組成。 我已經像這樣設置了服務器端代碼(Spring):

    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody
    Upload multipleSave(MultipartHttpServletRequest request)
    {
        Upload upload = new Upload();
        Iterator<String> iterator = request.getFileNames();
        while (iterator.hasNext())
        {
            MultipartFile file = request.getFile(iterator.next());

            try
            {
                System.out.println(MessageFormat.format("File Length: {0}", Arrays.toString(file.getBytes())));
                System.out.println("File Type: " + file.getContentType());
                upload.setContent(file.getBytes());
                upload.setDocId(id++);
                upload.setError(null);
                upload.setName(file.getName());
                upload.setSize(file.getSize());
                fileList.put(upload.getDocId().toString(), upload);
            } catch (Exception e)
            {
                System.out.println("Error occurred: " + e);
                upload.setError("500: Something went wrong!");
            }
        }

        return upload;
    }

和客戶端代碼是這樣的:

  function processFileUpload()
  {
    console.log("fileupload clicked");
    var formData = new FormData();
    formData.append("file", files[0]);
    $.ajax({dataType: 'json',
      url: "/SpringJqueryFileUpload/upload",
      data: formData,
      type: "POST",
      enctype: 'multipart/form-data',
      processData: false,
      contentType: false,
      success: function (result) {
        alert('success' + JSON.stringify(result));
      },
      error: function (result) {
        alert('error' + JSON.stringify(result));
      }
    });
  }

當我提交時,服務器將對此作出響應:

java.lang.IllegalArgumentException: No converter found for return value of type: class com.upload.model.Upload

我想知道錯誤。 我可以在這里丟失一些東西嗎?

我會嘗試將您的注釋更改為:

@RequestMapping(method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)

並確保在路徑上正確安裝Jackson(Spring用於JSON序列化)。 另外,請確保您的Upload類是可序列化的,例如不是private或類似的東西。 如果它只是一個普通的Java bean類型類,那應該沒問題。

最后,如果這樣不起作用,您可以使用以下命令打開Spring調試日志:

log4j.category.org.springframework.web=ALL

在您的log4j.properties文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM