So I am still lost here. I have a form with a modal. The modal is used to "attach" a file. I want to temporarily store the file on the server then email it with rest of form input values when form is submitted. I am using this ajax call to post this to the server so that the whole form doesn't submit and refresh the page. But to save it via ajax call, I need to serialize the file and so then it is not saving correctly. I have multiple issues with this... one is that the document is saving as null and will not open, and I believe the reason is I do not know how to grab the name of the file. Document is usually used to create a new item in my sql database document table so by calling it this way I am getting an empty entry in my database. Any ideas of a better way to do this? I have also tried saving as a multipart file, but I can't get the ajax post to work with that because it seems to need to be serialized. Any ideas are much appreciated. Thanks!
Here is my controller:
@RequestMapping(value="/directBindAjax", method=RequestMethod.POST)
public @ResponseBody Document docSend(@ModelAttribute(value="document") Document document, Model model) throws IOException {
FileOutputStream fout = new FileOutputStream(storageService.getUploadDir() + document.getStorage());
ObjectOutputStream oos = new ObjectOutputStream(fout);
model.addAttribute("document", document);
return document;
}
Here is my ajax call
$('#attachTheDoc').on('click', function(event){
var data = $('#newRequiredDocForm').serialize();
$.ajax({
type: "POST",
url: "/directBindAjax",
data: data,
processData: false,
cache: false,
success: function(data, jqXHR){
alert("Your files have been saved");
}
});
});
Here is the error I get when I try to do it the way suggested in the other post about sending a form via ajax. I also get a 403 error in my web browser.
Here is my form html:
<form enctype="multipart/form-data" id="newRequiredDocForm" th:action="@{/directBindAjax}" method="post" th:object="${newDoc}">
<br/>
<div class="row">
<div class="col-xs-4 col-sm-3 text-right"><label class="modalLabel">Type:</label></div>
<div class="col-xs-8 col-sm-7">
<select class="form-control" id="type">
<option value="Invoice">Invoice</option>
<option value="Binder">Binder</option>
<option value="Application">Application</option>
</select>
</div>
</div>
<br/>
<div class="row">
<div class="col-xs-4 col-sm-3 text-right">
<label class="modalLabel">File:</label>
</div>
<div class="col-xs-8 col-sm-7">
<input type="file" id="file" name="upfile" multiple="multiple" style="margin-right:-20px;"/>
</div>
</div>
<br/><br/>
<div style="text-align: right;">
<input type="button" id="attachTheDoc" class="btn btn-docModal" value="Upload"/>
</div>
</form>