我需要使用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中的字段“file”到空。
当我检查Google Chrome中的网络标签时,它会显示在“请求有效负载”中
------ WebKitFormBoundarymChhAWgmzsVyaJ2P 内容处理:表格数据; NAME = “文件”;文件名= “Cargo_AC123TU2015991946296415.pdf” 内容类型:application / pdf
------ WebKitFormBoundarymChhAWgmzsVyaJ2P -
似乎我正在发送一个空文件。我不知道我做错了什么。
答案 0 :(得分: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.";
}
}
希望这会对你有所帮助
由于