我们先编写页面并导入jquery的包
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-1.8.3.min.js"></script>
</head>
<body>
<input type="file" name="file"><br>
<input type="button" value="上传"><br>
</body>
</html>
然后为它添加相应的ajax代码,对于jquery如何使用我就不再讲解,大家可以去以下网址进行学习:jQuery 教程 | 菜鸟教程 (runoob.com)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-1.8.3.min.js"></script>
</head>
<body>
<input type="file" name="file"><br>
<input type="button" value="上传"><br>
</body>
</html>
<script>
$(":button").click(function () {
var datas = new FormData();
datas.append("file",$(":file").get(0).files[0]);
$.ajax({
url:"ser01",
type:"post",
dataType:"json",
processData: false,
contentType:false,
data:datas,
success:function (data) {
console.log(data)
}
})
})
</script>
接下我们编写后端代码:
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
try {
List<FileItem> fileItems = upload.parseRequest(req);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField())
{
// 是普通表单元素
System.out.println("普通表单元素"+fileItem.getName()+"="+fileItem.getString());
}
else
{
// 是文件
System.out.println("文件:"+fileItem.getName()+" 文件流inputStream:"+fileItem.getInputStream());
int len;
byte buffer[] = new byte[1024*10];
BufferedInputStream bis = new BufferedInputStream(fileItem.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:/"+fileItem.getName()));
while ((len=bis.read(buffer))!=-1)
{
bos.write(buffer,0,len);
}
bos.flush();
bis.close();
bos.flush();
}
}
Map<String,Object> result = new LinkedHashMap<>();
result.put("code","200");
result.put("msg","上传成功");
result.put("data","");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write(JSONObject.toJSONString(result));
} catch (FileUploadException e) {
e.printStackTrace();
}
}
在我们进行调用后,上传的文件确实在后台服务器中被接收到了,而且也成功的被写入到了E盘中