[英]Ajax form submission with file upload not working Spring MVC
Ajax代碼:
var str = $("#observationForm").serialize();
$.ajax({
type : "post",
data : str,
url : "updateObservation",
async : true,
/* dataType : "multipart/form-data", */
success : function() {
alert("success");
}
});
JSP-Spring形式:
<form:form modelAttribute="ObservationModal" action="updateObservation" id="observationForm">
<label class="control-label">Tooth No</label>
<input type="text" class="form-control" name="tooth" id="tooth" placeholder="Enter tooth no" />
<label class="control-label">Uploaded file(PDF)</label>
<input type="file" class="form-control" name="attachment" value="" id="attachment" placeholder="" />
<input type="button" value="Save" onclick="updateObservation();" />
</form:form>
控制器類
@RequestMapping(value = "/updateObservation", method = RequestMethod.POST)
public @ResponseBody String updateObservation(
@ModelAttribute("ObservationModal") ObservationModal formObj) {
String result = "";
System.out.println(":" + formObj.getTooth());
System.out.println(formObj.getAttachment());
return result;
}
模態類
public class ObservationModal implements Serializable {
int tooth;
private List<MultipartFile> attachment;
public int getTooth() {
return tooth;
}
public void setTooth(int tooth) {
this.tooth = tooth;
}
public List<MultipartFile> getAttachment() {
return attachment;
}
public void setAttachment(List<MultipartFile> attachment) {
this.attachment = attachment;
}
}
我無法在控制器中獲取值文本框值或附件。 ObservationModal始終為null
要進行ajax調用,URL必須為“ / projectName / actualurl”類型。 在您的情況下,URL:'/ projectName / updateObservation'。 並且還將dataType:'text'添加到調用中。
無法使用AJAX上傳文件。 為此,您可以使用formdata進行文件上傳,但這僅適用於受html5支持的瀏覽器
var form = $('form')[0]; // You need to use standart javascript object here
var formData = new FormData(form);
而且,如果您希望它甚至適用於較舊的瀏覽器,則可以將iframe與form一起用於文件上傳。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.