简体   繁体   中英

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. I have read that it is possible but doesn't work in my project. I'm working with Jquery and 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:

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:

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.

When I check the network tab in Google Chrome, it shows in Request Payload:

------WebKitFormBoundarymChhAWgmzsVyaJ2P Content-Disposition: form-data; name="file"; filename="Cargo_AC123TU2015991946296415.pdf" Content-Type: application/pdf

------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

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

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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