获取错误所需的请求部分 'logoURL' 不存在
Getting error Required request part 'logoURL' is not present
我正在尝试保存带有图像徽标的简单表单,但我在浏览器控制台中收到 HTTP 400。并且 所需的请求部分 'logoURL' 不存在 请查看我的代码并让我知道我在这里做错了什么。
Master Ajax: 我为Ajax
发送请求和响应而制作的class
class MasterAjax{
constructor(){
this.requestType = null;
this.url = null;
this.timeout = 100000;
this.enctype = null;
this.data = null;
this.processData = null;
this.contentType = null;
this.responseData = null;
this.responseStatus = null;
this.responseStatusCode = null;
}
requestData(callBack){
var parameterError=false;
if(null == this.requestType){
parameterError=true;
console.log("Error: Request Type can't be null");
}
if(null === this.url || undefined === this.url || "undefined" === this.url){
parameterError=true;
console.log("Error: URL can't be null");
}
if(null == this.data || this.data.length <= 0){
//console.log("Warning: Data is null");
}
if(parameterError === false){
/*toggleSpinnerOn(); */
$.ajax({
type : this.requestType,
enctype : this.enctype,
processData : this.processData,
contentType : this.contentType,
// url : global_contextPath+"/"+this.url,
url : global_contextPath+"/"+this.url,
data: this.data,
timeout : this.timeout,
success : function(responseData,textStatus) {
callBack(responseData,textStatus);
},
error : function(responseData,textStatus) {
callBack(responseData,textStatus);
}
});
}
}
}
商店形式
<%@include file="/WEB-INF/views/Store/StoreTemplet/Header.jsp"%>
<%-- <script src="<c:url value="/resources/js/testEstimation/TestEstimationPhases.js"/>"></script> --%>
<script type="text/javascript" charset="utf8" src="<c:url value="/js/storejs/storejs.js"/>"></script>
<!-- Content wrapper start -->
<div class="content-wrapper">
<div class="card">
<h2 class="card-title">New Store</h2>
<form name="storeForms" method="POST" enctype="multipart/form-data">
<!-- Hidden For Update employee -->
<input type="hidden" />
<!-- First row -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Name</label>
<input type="text" class="form-control"
id="storeName" placeholder="Store Name" required="required" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Country</label>
<input type="text" id="country" class="form-control" />
</div>
</div>
<!-- Second row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">City</label>
<input type="text" id="city" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Street</label>
<input type="text" id="street" class="form-control" />
</div>
</div>
<!-- Third row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Address</label>
<input type="text" id="address" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Zip Code</label>
<input type="text" id="zipCode" class="form-control" />
</div>
</div>
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Description</label>
<input type="text" id="storeDescription"
class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Store Timings</label>
<input type="text" id="storeOpenTime" class="form-control" />
</div>
</div>
<div class="custom-file">
<input type="file" id="file-input-2" data-default-value="Store Logo" />
<label for="file-input-2">Store logo</label>
</div>
<!-- Submit button container -->
<div class="text-right">
<!-- text-right = text-align: right -->
<input class="btn btn-primary" type="button" onclick="saveStore()" value="Add Store">
</div>
</form>
</div>
</div>
<!-- Content wrapper end -->
<%@include file="/WEB-INF/views/Store/StoreTemplet/Footer.jsp"%>
Ajax请求方法
function saveStore(){
let formData = new FormData();
//formData.append("key" , Value ) ;
formData.append("storeName", $("#storeName").val());
formData.append("country", $("#country").val());
formData.append("city", $("#city").val());
formData.append("street", $("#street").val());
formData.append("address", $("#address").val());
formData.append("zipCode", $("#zipCode").val());
formData.append("storeDescription", $("#storeDescription").val());
formData.append("storeOpenTime", $("#storeOpenTime").val());
formData.append('logoFile', $("#logoURL").val());
var obj = new MasterAjax();
obj.requestType = "POST";
obj.url = "store/saveStore";
obj.data = formData;
obj.enctype ="multipart/form-data";
obj.contentType = false;
obj.processData = false;
obj.dataType= "json";
console.log("---------------------------")
for (var pair of formData.entries()) {
console.log(pair[0]+ ': ' + pair[1]);
}
console.log("---------------------------")
obj.requestData(function(responseData){
console.log(responseData);
if(responseData.status == "OK" || responseData.status == "ok"){
alert("success");
console.log(responseData)
}else{
alert(" failed");
console.log(responseData)
}
});
}
控制器方法
@Controller
@RequestMapping("/store")
public class StoreController {
@ResponseBody
@RequestMapping(value = "/saveStore" , method = {RequestMethod.POST},consumes = {"multipart/form-data"})
public APIResponseModal saveStore(@ModelAttribute("storeForm") StoresDTO store,
BindingResult bres,
@RequestParam("logoURL") MultipartFile file) {
logger.info("Store Save MEthod callled !!!!!!!!");
Stores storeModal = new Stores();
String logopath = "";
APIResponseModal apiResponse = new Utils().getDefaultApiResponse();
List<String> errorList = new ArrayList<String>();
try {
if(store !=null){
storeModal = new Stores(store);
if(!file.isEmpty()) {
if(file.getSize()>1000000) {//1000000 bytes == 1 mb
errorList.add("File size should be less than 1 MB");
// return AJax
}
logopath = Utils.storeLogoPath(file);
}
storeService.saveStore(storeModal, errorList,logopath);
if(errorList.isEmpty() && !Utils.isNotNull(errorList)) {
apiResponse.setStatus(HttpStatus.OK);
apiResponse.setData("--");
apiResponse.setMessage("Store Saved Successfully !!");
}else {
apiResponse.setMessage("Failed to save store !!");
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
}
}
} catch (Exception e) {
e.printStackTrace();
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
apiResponse.setData("--");
apiResponse.setMessage("Error Occured at our end !!");
}
logger.info("API RESPONSE:: ::"+ apiResponse);
return apiResponse;
}
}
保存存储方法
@Override
@Transactional
public void saveStore(Stores store,List<String> errorList,String logoPath) {
try {
if(Utils.isNotNull(store)) {
if(Utils.isNotNull(store.getStoreName())
&Utils.isNotNull(store.getAddress())
&Utils.isNotNull(store.getCountry())
&Utils.isNotNull(store.getCity())
&Utils.isNotNull(store.getStreet())
&Utils.isNotNull(store.getStoreOpenTime())
&Utils.isNotNull(store.getZipCode())
&Utils.isNotNull(store.getStoreDescription())
) {
store.setAddedAt(new java.sql.Timestamp(System.currentTimeMillis()));
store.setStoreOwner(1);
store.setUniqueStoreCode(store.getStoreName().substring(0,2)+Utils.RandomAlphaString());
store.setStoreStatus(Constants.storeStatus.OPEN);
store.setLogoURL(logoPath);
entityManager.merge(store);
}else {
errorList.add("Please Enter required Details !");
}
}else {
errorList.add("Please Enter required Details !");
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Exception Occured in Save Store Method : " + e.getMessage());
errorList.add("Error Occured at our End we are Sorry !! Please try again later");
}
}
IDE 控制台
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'logoURL' is not present]
浏览器控制台
Status400
VersionHTTP/1.1
Transferred1.26 KB (1.10 KB size)
Referrer Policystrict-origin-when-cross-origin
您似乎缺少需要添加到表单字段的 name
参数
所以你输入的字段应该是
<input type="text" id="address" name="address" class="form-control" />
将相同的内容添加到您的 file
字段。
还有你的 saveStore
函数在做什么?
这里的代码有多个问题,首先我从控制器中删除了 @RequestParam("logoURL") MultipartFile file
参数,因为我在我的 DTO 中发送文件,所以这里不需要它。(如果您正在使用 spring 形式发送数据而不是 AJAX) 所以控制器现在看起来像
@ResponseBody
@RequestMapping(value = "/saveStore" , method = {RequestMethod.POST})
public APIResponseModal saveStore(@ModelAttribute StoresDTO store,HttpSession session)
其他问题在 Ajax 请求文件上,我在第 14 行向控制器发送数据,代码是 formData.append('logoFile', $("#logoURL").val());
,这里不正确我只是发送文件名而不是文件这就是我收到类型不匹配异常的原因因为我的 DTO 变量是 Multipart 类型并且我试图在此处发送字符串所以我在此处替换的代码是 formData.append('logoFile', $('input[type=file]')[0].files[0]);
我正在尝试保存带有图像徽标的简单表单,但我在浏览器控制台中收到 HTTP 400。并且 所需的请求部分 'logoURL' 不存在 请查看我的代码并让我知道我在这里做错了什么。
Master Ajax: 我为Ajax
发送请求和响应而制作的classclass MasterAjax{
constructor(){
this.requestType = null;
this.url = null;
this.timeout = 100000;
this.enctype = null;
this.data = null;
this.processData = null;
this.contentType = null;
this.responseData = null;
this.responseStatus = null;
this.responseStatusCode = null;
}
requestData(callBack){
var parameterError=false;
if(null == this.requestType){
parameterError=true;
console.log("Error: Request Type can't be null");
}
if(null === this.url || undefined === this.url || "undefined" === this.url){
parameterError=true;
console.log("Error: URL can't be null");
}
if(null == this.data || this.data.length <= 0){
//console.log("Warning: Data is null");
}
if(parameterError === false){
/*toggleSpinnerOn(); */
$.ajax({
type : this.requestType,
enctype : this.enctype,
processData : this.processData,
contentType : this.contentType,
// url : global_contextPath+"/"+this.url,
url : global_contextPath+"/"+this.url,
data: this.data,
timeout : this.timeout,
success : function(responseData,textStatus) {
callBack(responseData,textStatus);
},
error : function(responseData,textStatus) {
callBack(responseData,textStatus);
}
});
}
}
}
商店形式
<%@include file="/WEB-INF/views/Store/StoreTemplet/Header.jsp"%>
<%-- <script src="<c:url value="/resources/js/testEstimation/TestEstimationPhases.js"/>"></script> --%>
<script type="text/javascript" charset="utf8" src="<c:url value="/js/storejs/storejs.js"/>"></script>
<!-- Content wrapper start -->
<div class="content-wrapper">
<div class="card">
<h2 class="card-title">New Store</h2>
<form name="storeForms" method="POST" enctype="multipart/form-data">
<!-- Hidden For Update employee -->
<input type="hidden" />
<!-- First row -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Name</label>
<input type="text" class="form-control"
id="storeName" placeholder="Store Name" required="required" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Country</label>
<input type="text" id="country" class="form-control" />
</div>
</div>
<!-- Second row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">City</label>
<input type="text" id="city" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Street</label>
<input type="text" id="street" class="form-control" />
</div>
</div>
<!-- Third row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Address</label>
<input type="text" id="address" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Zip Code</label>
<input type="text" id="zipCode" class="form-control" />
</div>
</div>
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Description</label>
<input type="text" id="storeDescription"
class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Store Timings</label>
<input type="text" id="storeOpenTime" class="form-control" />
</div>
</div>
<div class="custom-file">
<input type="file" id="file-input-2" data-default-value="Store Logo" />
<label for="file-input-2">Store logo</label>
</div>
<!-- Submit button container -->
<div class="text-right">
<!-- text-right = text-align: right -->
<input class="btn btn-primary" type="button" onclick="saveStore()" value="Add Store">
</div>
</form>
</div>
</div>
<!-- Content wrapper end -->
<%@include file="/WEB-INF/views/Store/StoreTemplet/Footer.jsp"%>
Ajax请求方法
function saveStore(){
let formData = new FormData();
//formData.append("key" , Value ) ;
formData.append("storeName", $("#storeName").val());
formData.append("country", $("#country").val());
formData.append("city", $("#city").val());
formData.append("street", $("#street").val());
formData.append("address", $("#address").val());
formData.append("zipCode", $("#zipCode").val());
formData.append("storeDescription", $("#storeDescription").val());
formData.append("storeOpenTime", $("#storeOpenTime").val());
formData.append('logoFile', $("#logoURL").val());
var obj = new MasterAjax();
obj.requestType = "POST";
obj.url = "store/saveStore";
obj.data = formData;
obj.enctype ="multipart/form-data";
obj.contentType = false;
obj.processData = false;
obj.dataType= "json";
console.log("---------------------------")
for (var pair of formData.entries()) {
console.log(pair[0]+ ': ' + pair[1]);
}
console.log("---------------------------")
obj.requestData(function(responseData){
console.log(responseData);
if(responseData.status == "OK" || responseData.status == "ok"){
alert("success");
console.log(responseData)
}else{
alert(" failed");
console.log(responseData)
}
});
}
控制器方法
@Controller
@RequestMapping("/store")
public class StoreController {
@ResponseBody
@RequestMapping(value = "/saveStore" , method = {RequestMethod.POST},consumes = {"multipart/form-data"})
public APIResponseModal saveStore(@ModelAttribute("storeForm") StoresDTO store,
BindingResult bres,
@RequestParam("logoURL") MultipartFile file) {
logger.info("Store Save MEthod callled !!!!!!!!");
Stores storeModal = new Stores();
String logopath = "";
APIResponseModal apiResponse = new Utils().getDefaultApiResponse();
List<String> errorList = new ArrayList<String>();
try {
if(store !=null){
storeModal = new Stores(store);
if(!file.isEmpty()) {
if(file.getSize()>1000000) {//1000000 bytes == 1 mb
errorList.add("File size should be less than 1 MB");
// return AJax
}
logopath = Utils.storeLogoPath(file);
}
storeService.saveStore(storeModal, errorList,logopath);
if(errorList.isEmpty() && !Utils.isNotNull(errorList)) {
apiResponse.setStatus(HttpStatus.OK);
apiResponse.setData("--");
apiResponse.setMessage("Store Saved Successfully !!");
}else {
apiResponse.setMessage("Failed to save store !!");
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
}
}
} catch (Exception e) {
e.printStackTrace();
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
apiResponse.setData("--");
apiResponse.setMessage("Error Occured at our end !!");
}
logger.info("API RESPONSE:: ::"+ apiResponse);
return apiResponse;
}
}
保存存储方法
@Override
@Transactional
public void saveStore(Stores store,List<String> errorList,String logoPath) {
try {
if(Utils.isNotNull(store)) {
if(Utils.isNotNull(store.getStoreName())
&Utils.isNotNull(store.getAddress())
&Utils.isNotNull(store.getCountry())
&Utils.isNotNull(store.getCity())
&Utils.isNotNull(store.getStreet())
&Utils.isNotNull(store.getStoreOpenTime())
&Utils.isNotNull(store.getZipCode())
&Utils.isNotNull(store.getStoreDescription())
) {
store.setAddedAt(new java.sql.Timestamp(System.currentTimeMillis()));
store.setStoreOwner(1);
store.setUniqueStoreCode(store.getStoreName().substring(0,2)+Utils.RandomAlphaString());
store.setStoreStatus(Constants.storeStatus.OPEN);
store.setLogoURL(logoPath);
entityManager.merge(store);
}else {
errorList.add("Please Enter required Details !");
}
}else {
errorList.add("Please Enter required Details !");
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Exception Occured in Save Store Method : " + e.getMessage());
errorList.add("Error Occured at our End we are Sorry !! Please try again later");
}
}
IDE 控制台
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'logoURL' is not present]
浏览器控制台
Status400
VersionHTTP/1.1
Transferred1.26 KB (1.10 KB size)
Referrer Policystrict-origin-when-cross-origin
您似乎缺少需要添加到表单字段的 name
参数
所以你输入的字段应该是
<input type="text" id="address" name="address" class="form-control" />
将相同的内容添加到您的 file
字段。
还有你的 saveStore
函数在做什么?
这里的代码有多个问题,首先我从控制器中删除了 @RequestParam("logoURL") MultipartFile file
参数,因为我在我的 DTO 中发送文件,所以这里不需要它。(如果您正在使用 spring 形式发送数据而不是 AJAX) 所以控制器现在看起来像
@ResponseBody
@RequestMapping(value = "/saveStore" , method = {RequestMethod.POST})
public APIResponseModal saveStore(@ModelAttribute StoresDTO store,HttpSession session)
其他问题在 Ajax 请求文件上,我在第 14 行向控制器发送数据,代码是 formData.append('logoFile', $("#logoURL").val());
,这里不正确我只是发送文件名而不是文件这就是我收到类型不匹配异常的原因因为我的 DTO 变量是 Multipart 类型并且我试图在此处发送字符串所以我在此处替换的代码是 formData.append('logoFile', $('input[type=file]')[0].files[0]);