【发布时间】:2017-01-13 06:23:59
【问题描述】:
我的 jsp 中有一个文件上传组件,我只接受 json 格式的文件。我想获取json文件并将其传递给spring并在spring中对json对象进行操作。
我的 javascript 如下所示
var file = this.files[0];
var reader = new FileReader();
var oMyForm = new FormData();
oMyForm.append("file", this.files[0]);
console.log('reader='+JSON.stringify(reader)) // this does not print any it prints empty as "reader={}"
console.log('oMyForm ='+JSON.stringify(oMyForm )) // this does not print any it prints empty as "oMyForm={}"
var urlpath = "<%=request.getContextPath()%>/fileUpload";
$.ajax({
data : JSON.stringify(reader),
type : 'POST',
dataType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url : urlpath,
success : function(data){
}
});
Java 类
@RequestMapping(value= "/fileUpload", method=RequestMethod.POST,consumes="application/json")
public void fileUpload(){
//here i want to get the json object and do parsing and manipulations on the object
System.out.println(" uploaded!");
}
同样,当我上传文件时它会碰到控制器类,但在浏览器控制台中它会抛出错误
“NetworkError: 404 Not Found - http://localhost:8080/proj/fileUpload”
但是当我尝试从JSON.stringify(hardcoded)打印硬编码值时
Json 文件内容:
{'Gyr-x':10.11,'Gyr-y':9.66,'Gyr-z':10.93,'Temparature':30,'Pressure':101,'Humidity':15,'deviceId':1}
【问题讨论】:
-
你怎么知道它命中了服务器?打印硬编码值是什么意思?在服务器还是客户端?
-
它命中服务器 sysout 正在打印。打印硬编码值,而不是上传文件,而是将 json 放入变量并在浏览器控制台中打印
标签: javascript json ajax spring