使用Spring MVC和jQuery(Ajax)将文件上传到Google Cloud时出错

时间:2016-03-07 11:31:39

标签: jquery ajax spring-mvc google-cloud-storage

我正在使用Spring MVC和Ajax从网页上传文件到服务器。它适用于普通客户端服务器模型但是当我在谷歌云中托管战争时,文件没有上传它会引发错误。以下是我试过的代码。

Jquery:

var jForm = new FormData();
jForm.append("selectSourceFile", $('#selectSourceFile').get(0).files[0]);

$.ajax({
    type: 'POST',
    data: jForm,
    contentType: false,
    enctype:"multipart/form-data",  
    processData: false,
    async : false,
    url: "uploadInputFile",
    success: function(response) {
        moveNext();             
    },
    error : function(msg) {
    }
});

控制器:

@RequestMapping(value = "/uploadInputFile", method = RequestMethod.POST)
public void uploadInputFile(HttpSession session, @RequestParam("selectSourceFile") MultipartFile file)
{
    if(file.getSize() != 0)
    {
        byte[] bytes = file.getBytes();
        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(session.getAttribute("appFolderPath") + file.getOriginalFilename())));
        outStream.write(bytes);

        if(outStream != null)
        {
            outStream.close();
        }
    }
}

Servlet xml:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
    <property name="maxUploadSize" value="1000000" />
</bean>

浏览器出错: POST 网址/ uploadInputFile 500(INKApi错误)

尝试过使用GMulitpart而不是Multipart!

<bean id="multipartResolver" class="org.gmr.web.multipart.GMultipartResolver"> 
    <property name="maxUploadSize" value="1000000" />
</bean>

1 个答案:

答案 0 :(得分:0)

FormData构造函数在其构造函数中采用表单而不是文件。使用FormData.append添加文件。

var jForm = new FormData();
jForm.append('selectSourceFile', $('#selectSourceFile').get(0).files[0]);
$.ajax({
    type: 'POST',
    data: jForm,
    contentType: false,
    processData: false,
    ...
});