Ajax实现文件上传详解

it2025-03-28  9

在做web项目中,需要实现ajax做一个头像上传功能。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="../upImg" method="post"> <h3>ajax实现文件上传功能</h3> <img class="img-circle" src="../img/11.jpg" alt=""/><br/> <input type="hidden" name="imgPath" id="imgPath"/> <input type="file" name="file" id="upfile" /><button class="btn" onclick="upload()">上传</button><br/> </form> </body> <script src="../js/jquery-3.5.1.js"></script> <script src="../js/ajaxfileupload.js"></script> <script> function upload() { $.ajaxFileUpload({ url:"../upload", fileElementId:"upfile", dataType:"string", success:function (data) { console.log(data); $("#imgPath").val(data); $(".img-circle").attr("src","../upload/"+data); } }) } </script> </html>

jquery和ajax文件上传js自取 提取码:ukem

然后接下来就是servlet部分了。当ajax向servlet发送了请求,则可以通过servlet处理请求了。

package com.lovo.servlet; /** * @auther luo * @create 2020-10-21 17:11 */ import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; @WebServlet("/upload") /** *因为上传图片只能使用二进制数据上传,所以需要加上@multipartConfig注解,不然上传不了 */ @MultipartConfig public class UploadFileServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*设置服务端发送的类型及采用的编码方式*/ response.setContentType("text/html;charset=utf-8"); /*获得文件对象*/ Part part = request.getPart("file"); /*获得报头的内容*/ String header = part.getHeader("content-disposition"); /*获得报头中filename的值,如filename=abc.jpj,则path为abc.jpg*/ String path = header.substring(header.indexOf("filename=") + 10, header.length() - 1); // 获取文件的真实路径 String realPath = this.getServletContext().getRealPath("/upload"); String newFileName = generateUploadFileName(getRealName(path)); /*获得文件对象*/ File file = new File(realPath); /*如果文件目录不存在,则创建目录*/ if (!file.exists()) { file.mkdirs(); } // 获取输入流 InputStream inputStream = part.getInputStream(); // 定义输出流 FileOutputStream outputStream = new FileOutputStream(new File(file, newFileName)); // 从输入流中读入数据并写到输出字节流中 int len = -1; byte[] bytes = new byte[1024]; while ((len = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } // 关闭资源 outputStream.close(); inputStream.close(); // 删除临时文件 part.delete(); response.getWriter().print(newFileName); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * 获得文件的真实名字,并且排除名字中的非法字符 * @param path * @return */ public static String getRealName(String path) { int index = path.lastIndexOf("\\"); if (index == -1) { index = path.lastIndexOf("/"); } return path.substring(index + 1); } /** * 获得唯一的文件名字 * @param name * @return */ public static String generateUploadFileName(String name){ String suffixName = name.substring(name.lastIndexOf(".")); UUID uuid = UUID.randomUUID(); return uuid+suffixName; } }

当servlet处理好了请求,把文件保存在指定文件夹之后,就可以把处理过后的文件名字发回给ajax,然后通过回调函数,用jquery把返回的文件名字重新赋值给img的src属性,从而实现预览效果。

最新回复(0)