首页 前端知识 利用jquery的ajax实现文件上传

利用jquery的ajax实现文件上传

2024-04-03 12:04:28 前端知识 前端哥 279 898 我要收藏

我们先编写页面并导入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盘中

 

 

 

转载请注明出处或者链接地址:https://www.qianduange.cn//article/4454.html
标签
servlet
评论
发布的文章

java解析超大json文件数据

2024-04-19 21:04:10

头歌-JavaScript基础

2024-04-19 21:04:54

C#Json序列化及反序列化

2024-04-19 21:04:40

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!