vlambda博客
学习文章列表

Ajax+Java实现图片上传并回显

FormData是XMLHttpRequest Level 2提供的一个接口对象,可以使用该对象来模拟和处理表单并方便的进行文件上传操作。


下面我们看看怎么基于FormData来实现ajax文件上传功能。


前端jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="path" value="${pageContext.request.contextPath}"></c:set><!DOCTYPE html><html><head><meta charset="UTF-8"><title>ajax图片上传</title></head><body> <form id="myform" enctype="multipart/form-data"> <input type="file" name="pic" id="pic"> <p id="pimg"></p> </form></body></html><script type="text/javascript" src="${path}/js/jquery-3.6.0.min.js"></script><script type="text/javascript"> $(function (){ $("#pic").change(function (){ //formData可以通过ajax来提交表单 var formData=new FormData(document.getElementById("myform")); //添加图片上传的控件 formData.append("pic",document.getElementById("pic")); $.ajax({ url:"${path}/manage/product?action=uploadPic", type:"post", data:formData, //上传图片必须指定 //不设置contentType头 contentType:false, //不让jquery处理发送的数据 processData:false, success:function (data){ if(data!=""){ $("#pimg").html("<img src='${path}/images/"+data+"' style='width:100px;'>"); } } }); }); });</script>


后端Servlet

@MultipartConfig()@WebServlet("/manage/product")public class ProductServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String action=request.getParameter("action"); if("uploadPic".equals(action)){ this.list(request,response); } }  //ajax上传图片 private void uploadPic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part part=request.getPart("pic"); String filename=""; //获得请求的报头信息 //格式例如:form-data; name="pic"; filename="6.jpg" String head=part.getHeader("content-disposition"); if(head.indexOf(".")>0){ //获取最后面.的位置 int index=head.lastIndexOf("."); //获取上传图片的后缀名 String fileext=head.substring(index,head.length()-1); //生成新的图片的名字 //UUID 通过计算当前时间戳、随机数和机器MAC地址得到 唯一的 filename=UUID.randomUUID().toString()+fileext; //获得网站发布之后的根路径 String filepath=request.getServletContext().getRealPath("/")+"/images/"; //在指定位置写入指定名字的图片 part.write(filepath+filename); //释放内存中和图片有关的数据 part.delete(); //上传图片结束 } PrintWriter out=response.getWriter(); out.write(filename); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); }}


实现效果: