簡體   English   中英

使用ajax和spring上傳文件

[英]File upload using ajax and spring

我正在嘗試上傳文件並在服務器端讀取它。 但我無法讀取文件,而是出現異常

Required MultipartFile parameter 'file' is not present

下面是相同的代碼片段。 如果我在這里做錯了什么,你能告訴我嗎? 有沒有其他方法可以在服務器端讀取ajax請求發送的文件。

<form  id="dealform" method="post" enctype="multipart/form-data" type="file">
<input type="file" name="file" id="upload_file" style="visibility: hidden;width:0px;height:0px;"/><input id="fg-upload-button" type="submit" value="Upload" style="display:none;"/>
</form>

this.getRecord              = function(params)      {

            var file = $('#upload_file').prop("files")[0];

            $.ajax({
                url         : /Upload,
                data        : file,
                type        : 'POST',
                dataType    : 'json',
                timeout     : json_timeout,
                error       : function(){
                    that.notifyGetDataError('error getting:');                  
                },
                success     : function(data){
                    that.notifyGetDataSuccess();
                }
            });
        };

In the controller :

@RequestMapping(value = "/Upload.json", method = RequestMethod.POST)
    public ModelAndView getContents(@RequestParam("file") MultipartFile file) { 
}

Using the below in applicationContext.xml

<bean id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

該代碼將文件本身作為有效負載傳遞給您的服務器。 但是,您的控制器期望文件作為參數“file”的值發送

您將文件作為 dataType="json" 發送,這可能會導致您出現問題,因為您的內容類型是 multipart/form-data

按照此鏈接FormData 進行 ajax 文件上傳

您的問題的另一個鏈接是here

您可以點擊此鏈接,其中包含MultipartFile的控制器代碼

 data        : {file1:file}

並在控制器中

getContents(@RequestParam("file1") MultipartFile file)

在控制器方法中,只需將請求參數的名稱更改為數據:

@RequestMapping(value = "/Upload.json", method = RequestMethod.POST)
    public ModelAndView getContents(@RequestParam("data") MultipartFile file) { 
}

暫無
暫無

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

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