简体   繁体   English

使用ajax和spring portlet将文件从客户端上传到服务器端

[英]Upload a file from client side to server side with ajax and spring portlet

I need to upload a file from client side to server side with ajax. 我需要使用ajax将文件从客户端上传到服务器端。 I have read that it is possible but doesn't work in my project. 我读过有可能,但在我的项目中不起作用。 I'm working with Jquery and Spring Portlet. 我正在使用Jquery和Spring Portlet。

This is my code at client side: 这是我在客户端的代码:

<form method="post" id="formUploadFile">
    <input id="uprloadFile" type="file" name="file"/> 
    <input id="submitButton" type="button" value="Upload File" />
</form>

javascript: JavaScript的:

var dataFormulario = new FormData($('#formUploadFile')[0]);

$.ajax({
    url : accredit.cargarDocumentoURL,
    type : "POST",
    data : dataFormulario,
    cache: false,
    contentType: false, 
    processData: false,
    success : function(data) {
        alert("Success");
    },
    error : function(data) {
        alert("Error");
    }
});

I get the file in this method of my controller: 我通过控制器的这种方法获取文件:

@ResourceMapping("uploadFile")
public void uploadFile(ResourceResponse response,
        @ModelAttribute(value = "AccreditCommand") AccreditCommand accreditCommand) {
    System.out.println("File : " + accreditCommand.getFile());
    successResponse(response);
}

My object in ModelAttribute: 我在ModelAttribute中的对象:

public class AccreditCommand {

    private byte[] file;

    public byte[] getFile() {
        return file;
    }

    public void setFile(byte[] file) {
        this.file = file;
    }

}

There is no error in the log and the field "file" in AccreditCommand arrives empty. 日志中没有错误,并且AccreditCommand中的“文件”字段为空。

When I check the network tab in Google Chrome, it shows in Request Payload: 当我在Google Chrome浏览器中检查“网络”标签时,该标签显示在“请求有效载荷”中:

------WebKitFormBoundarymChhAWgmzsVyaJ2P Content-Disposition: form-data; ------ WebKitFormBoundarymChhAWgmzsVyaJ2P内容处置:form-data; name="file"; NAME = “文件”; filename="Cargo_AC123TU2015991946296415.pdf" Content-Type: application/pdf filename =“ Cargo_AC123TU2015991946296415.pdf”内容类型:application / pdf

------WebKitFormBoundarymChhAWgmzsVyaJ2P-- ------ WebKitFormBoundarymChhAWgmzsVyaJ2P--

It seems that I am sending an empty file. 看来我正在发送一个空文件。 I don't know What I am doing wrong. 我不知道我在做什么错。

Below is how I have successfully Uploaded file to server using ajax 以下是我如何使用ajax将文件成功上传到服务器的方法

JS JS

<script>
function uploadFormDataUsingAjax(){
  var uploadForm = new FormData();
  uploadForm.append("file", file2.files[0]);
  uploadForm.append("name", document.getElementById('fileName').value);
  $.ajax({
    url: 'http://localhost:8080/yourProjectName/uploadFile',
    data: uploadForm,
    dataType: 'text',
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
     console.log(data);
    }
  });
}
</script>

Html HTML

<form id="uploadFileForm" method="post" action="uploadFile" enctype="multipart/form-data">
  <!-- File input -->    
  AjaxFileToUpload<input name="file" id="file2" type="file" /><br/>
  Name: <input type="text" id="fileName" name="name"><br />
</form>
<button value="Submit" onclick="uploadFormDataUsingAjax()" >UploadFile</button> 

Controller 调节器

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
private @ResponseBody
String uploadFileHandler(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            String rootPath = "path To save your file/Spring_Upload";
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath()
                    + File.separator + name);
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            logger.info("Server File Location="
                    + serverFile.getAbsolutePath());

            return "You successfully uploaded file=" + name;
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name
                + " because the file was empty.";
    }
}

hope this will help you 希望这个能对您有所帮助

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM