簡體   English   中英

使用ajax和spring portlet將文件從客戶端上傳到服務器端

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

我需要使用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--

看來我正在發送一個空文件。 我不知道我在做什么錯。

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

希望這個能對您有所幫助

謝謝

暫無
暫無

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

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