通过Ajax传递的是字符串
如果想通过Ajax上传图片 需要先把图片转换成Base64的字符串
jsp端,通过JavaScript获得file文件域的图片 把图片转换成Base64字符串
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.5.1.min.js"></script> <head> <title>万码学堂wanmait</title> <meta name="author" content="万码学堂wanmait"> <meta> </head> <body> <input type="file" id="picture"> <script type="text/javascript"> $(function(){ //picture添加改变事件 $("#picture").change(function(){ //获得picture中间的图片 var picture = document.getElementById("picture").files[0]; var reader = new FileReader(); //设置FileReader打开图片的回调方法 reader.onload = function(event){ //以下代码在打开图片的时候执行 var base64 = event.target.result; //base64就是文件域中间选择的图片的base64字符串 console.log(base64); //利用Ajax上传文件 uploadFile(base64); }; //打开文件 reader.readAsDataURL(picture); }); }); function uploadFile(base64) { var url = "${pageContext.request.contextPath}/UploadController"; var data = {"picture":base64}; $.post(url,data,function(mes){ }); } </script> </body> </html>
UploadController.java
将Base64字符串转换成字节数组 将字节数组保存到硬盘,成为文件
package com.wanmait.test.controller; import org.apache.commons.io.FileUtils; import org.springframework.util.Base64Utils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.UUID; @WebServlet("/UploadController") public class UploadController extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String picture = request.getParameter("picture"); //获得图片的base64字符串 String temp[] = picture.split("base64,"); //picture字符串中 有base64,字符串 base64,之前的是头 base64,之后的是文件数据 String head = temp[0];//头 头中间有包含文件扩展名 String data = temp[1];//文件数据 int i = temp[0].lastIndexOf("/"); String fileext = temp[0].substring(i+1,temp[0].length()-1); //获得原来文件扩展名 String filename = UUID.randomUUID().toString()+"."+fileext; //上传保存的新文件名 //数据字符串变成二进制字节 byte[] dataB = Base64Utils.decodeFromString(data); //Base64Utils 工具类 spring-core.jar //项目下的images文件的绝对路径 String filepath = request.getServletContext().getRealPath("/images"); //字节数组保存到文件 FileUtils.writeByteArrayToFile(new File(filepath+"/"+filename),dataB); //FileUtils文件工具类 commons-io.jar } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
0条评论
点击登录参与评论