UploadServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@WebServlet
(
"/upload.do"
)
@MultipartConfig
public
class
UploadServlet
extends
HttpServlet {
@Override
public
void
doPost(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
// 获取文件路径
String filePath = WebUtil.getFilePath(request,
"files"
);
// 获取文件名
Part part = request.getPart(
"file"
);
String fileName = WebUtil.getFileName(request, part);
// 写入文件
part.write(filePath +
"/"
+ fileName);
// 返回结果
Map<String, Object> data =
new
HashMap<String, Object>();
data.put(
"fileName"
, fileName);
data.put(
"fileType"
, part.getContentType());
data.put(
"fileSize"
, part.getSize());
WebUtil.writeJson(response, data);
}
}
|
upload.html
1
2
3
4
5
6
7
8
9
10
|
<
form
id
=
"login_form"
action
=
"/upload.do"
method
=
"post"
enctype
=
"multipart/form-data"
>
<
p
>
<
label
for
=
"file"
>File:</
label
>
<
input
type
=
"file"
id
=
"file"
name
=
"file"
/>
</
p
>
<
p
>
<
button
type
=
"submit"
>Upload</
button
>
</
p
>
</
form
>
<
div
id
=
"console"
></
div
>
|
upload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
$(
function
() {
$(
'#login_form'
).ajaxForm({
beforeSubmit:
function
() {
if
($(
'#file'
).val() ==
''
) {
alert(
'Please choose a file!'
);
return
false
;
}
},
success:
function
(json) {
if
(json) {
var
html =
''
;
html +=
'<p>File Name: '
+ json.fileName +
'</p>'
;
html +=
'<p>File Type: '
+ json.fileType +
'</p>'
;
html +=
'<p>File Size: '
+ json.fileSize +
'</p>'
;
$(
'#console'
).html(html);
}
}
});
});
|
问题
在Chrome、Firefox上运行正常,在IE8+中运行时,提示下载,如下图:
'Content-Type:text/html; charset=utf-8'
- XX刚刚发现,IE10可以支持application/json格式的Response了,也就是说低于IE10版本一下的IE浏览器都需要使用text/html格式的Response。 (2年前)
- XX在Response头中指定Content-Type为text/html,而并非text/html,是可以解决问题的。这样返回给客户端的是一个JSON字符串(并非JSON对象),无需IE来解析。随后,使用JSON.parse()函数将JSON字符串解析为JSON对象即可。非常感谢你的回答! 但客户端JS代码有些不够优雅,能否通过统一的方式来设置呢?
百度了下,应该是没加dataType:
dataType
期望返回的数据类型。null、“xml”、“script”或者“json”其中之一。dataType提供一种方法,它规定了怎样处理服务器的响应。这个被直接地反映到jQuery.httpData方法中去。下面的值被支持:
'xml':如果dataType == 'xml',将把服务器响应作为XML来对待。同时,如果“success”回调方法被指定, 将传回responseXML值。
'json':如果dataType == 'json', 服务器响应将被求值,并传递到“success”回调方法,如果它被指定的话。
'script':如果dataType == 'script', 服务器响应将求值成纯文本。
默认值:null(服务器返回responseText值)