UploadServlet.java
@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 data = new HashMap();
data.put("fileName", fileName);
data.put("fileType", part.getContentType());
data.put("fileSize", part.getSize());
WebUtil.writeJson(response, data);
}
}
upload.html
File:
Upload
upload.js
$(function() {
$('#login_form').ajaxForm({
beforeSubmit: function() {
if ($('#file').val() == '') {
alert('Please choose a file!');
return false;
}
},
success: function(json) {
if (json) {
var html = '';
html += '
File Name: ' + json.fileName + '
';html += '
File Type: ' + json.fileType + '
';html += '
File Size: ' + json.fileSize + '
';$('#console').html(html);
}
}
});
});
问题 在Chrome、Firefox上运行正常,在IE8+中运行时,提示下载,如下图: