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

问题描述 投票:0回答:1

我需要使用ajax将文件从客户端上传到服务器端。 我读过有可能,但在我的项目中不起作用。 我正在使用Jquery和Spring Portlet。

这是我在客户端的代码:

<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");
    }
});

我通过控制器的这种方法获取文件:

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

我在ModelAttribute中的对象:

public class AccreditCommand {

    private byte[] file;

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

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

}

日志中没有错误,并且AccreditCommand中的“文件”字段为空。

当我在Google Chrome浏览器中检查“网络”标签时,该标签显示在“请求有效载荷”中:

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

------ WebKitFormBoundarymChhAWgmzsVyaJ2P--

看来我正在发送一个空文件。 我不知道我在做什么错。

java jquery ajax spring portlet
1个回答
1
投票

以下是我如何使用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> 

调节器

@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.";
    }
}

希望这个能对您有所帮助

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.