【发布时间】:2018-01-03 22:54:35
【问题描述】:
我是前端开发的新手,在为这个特定的表单设置拼凑解决方案时遇到了麻烦。
我已经创建了一个代表这个实例创建页面的jsp。这是一个包含许多下拉菜单和复选框的表单。我需要为其添加文件上传选项。
jsp是这样设置的……
<form class="form-horizontal" id="editInstanceForm" onsubmit="return false;"> ....
这是我的输入字段
<div class="form-group" id="uploadForm">
<label class="col-xs-4 control-label instanceDefaultLabel" for="fileSearchField">Default Location and Zoom:</label>
<div class="col-xs-3">
<input name="myFile" type="file" id="fileSearchField" multiple=false>
<button id="upload-button">Upload</button>
</div>
.....
</div>
现在我有一个 ajax 调用,在我意识到上传文件时整个表单都在尝试提交之前,我本来想使用它。在这里……
$('#upload-button').click( 'click',
function() {
var form = $('#fileSearchField')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/edit/uploadfile",
data: data,
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert("hi stuff worked");
},
error: function (e) {
alert("nope!");
}
});
}
);
我在研究如何使用 jQuery/ajax 和 Spring Boot 上传文件时得到了这个建议(我正在使用 Spring Boot 创建我的端点)。以下是我一直在阅读的一些文章,试图了解如何做到这一点...
https://www.mkyong.com/spring-boot/spring-boot-file-upload-example-ajax-and-rest/
还有更多。这似乎是解决方案,直到我意识到这是一个表单,我认为我需要一次保存所有字段。这意味着我必须修改已经创建的 ajax 函数来保存这个表单并将它传递到终点。现在我不知道如何将我的 MulitpartFile 作为这个不同功能的一部分。现有的是这样的……
$.ajax({
type: "POST",
url: webroot + "/viewerConfig/mapInstance/insertOrUpdate",
data: JSON.stringify(instanceData),
processData: false,
contentType: 'application/json',
success: function (data) {
if (data.status === "OK") {
alert("Instance created/updated successfully");
} else {
alert("Unknown error");
}
},
fail: function () {
alert("Unknown error");
},
error: function (a) {
alert("Unknown error");
}
});
});
这正是我卡住的地方,我需要指出正确和富有成效的方向。
我不知道这是否会有所帮助,但这是我的终点,看起来就像我必须通过添加文件参数来达到的终点...
@RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody BaseStatusResponse insertOrUpdate(final @RequestBody SaveAdminInstanceView newInstance, HttpServletResponse servletResponse,
@RequestParam MultipartFile file)
编辑: 我已经完成了一些 curl 故障排除,这是失败的 MulitpartFile。我按照建议通过了它,但我得到了这个异常:
org.springframework.web.multipart.MultipartException: The current request is not a multipart request</p><p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request
【问题讨论】:
标签: javascript jquery ajax spring spring-mvc