SpringMVC 通过ajax 实现文件的上传

使用form表单在springmvc 项目中上传文件,文件上传成功之后往往会跳转到其他的页面。但是有的时候,文件上传成功的同时,并不需要进行页面的跳转,可以通过ajax来实现文件的上传

下面我们来看看如何来实现:

方式1:前台从dom对象中获取到文件,并且将文件解析为Blob ,我们来看看页面代码:

复制代码
<input type="file" class="inputPic" />

javascript代码:

javascript 复制代码
$(".inputPic").change(function() {
		var serviceUrl = "http://localhost:8070/file/";
		var url = serviceUrl + "/upload_aj";
		var form = new FormData();
		var file=$(".inputPic")[0].files;
		
		console.log(file[0].name)
		form.append("myfile", new Blob(file));
		form.append("filename", file[0].name);
		var xhr = new XMLHttpRequest(); 
		xhr.open("post", url, true); // po
		xhr.upload.onloadstart = function() {// 上传开始执行方法
			ot = new Date().getTime(); // 设置上传开始时间
			oloaded = 0;// 设置上传开始时,以上传的文件大小为0
		};
		xhr.send(form); // 开始上传,发送form数据
		xhr.responseText = function(res) {
			console.log(res);
		}
		xhr.onreadystatechange = function(response) {
			console.log(response);
			if (response.target.readyState == '4') {
				var result = JSON.parse(response.target.response);
				console.log(result)
				if (Number(result.data) == 0) {
					alert(result.msg);
				} else {
					alert("图片上传成功");
				}
			}
		}
	});
	</script>

后台:

java 复制代码
	@ResponseBody
	@RequestMapping(value = "upload_aj", method = RequestMethod.POST)
	public Map<String, Object> upload_aj(HttpServletRequest request, @RequestParam("myfile") MultipartFile file) {
		try {
			String filename=request.getParameter("filename");
			byte[] bytes = file.getBytes();
			System.out.println(filename);
			Path path = Paths.get("保存路径/"+filename);
			Files.write(path, bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<>();
		map.put("msg", "文件上传成功");
		map.put("code", "0000");
		return map;
	}

方式2:前端将文件转换为base64,然后上传到后台:

前端代码:

java 复制代码
	<input type="file" class="inputPic" />

javascript代码:

javascript 复制代码
	$(".inputPic").change(function() {
		var serviceUrl = "http://localhost:8070/file/";
		var url = serviceUrl + "/upload_aj";
		var form = new FormData();
		var file=$(".inputPic")[0].files;
		
		console.log(file[0].name)
		form.append("myfile", new Blob(file));
		form.append("filename", file[0].name);
		var xhr = new XMLHttpRequest(); 
		xhr.open("post", url, true); // po
		xhr.upload.onloadstart = function() {// 上传开始执行方法
			ot = new Date().getTime(); // 设置上传开始时间
			oloaded = 0;// 设置上传开始时,以上传的文件大小为0
		};
		xhr.send(form); // 开始上传,发送form数据
		xhr.responseText = function(res) {
			console.log(res);
		}
		xhr.onreadystatechange = function(response) {
			console.log(response);
			if (response.target.readyState == '4') {
				var result = JSON.parse(response.target.response);
				console.log(result)
				if (Number(result.data) == 0) {
					alert(result.msg);
				} else {
					alert("图片上传成功");
				}
			}
		}
	});

后端代码:

java 复制代码
	@ResponseBody
	@RequestMapping(value = "upload_base", method = RequestMethod.POST)
	public Map<String, Object> upload_base(@RequestBody Map<String,Object> reqMap){
		
		try {
			String filename=reqMap.get("filename")+"";
			String filestr=reqMap.get("filestr")+"";
			System.out.println(filestr);	
			Base64FileConverter.decodeBase64ToFile(filestr,"C:\\upload/"+filename);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<>();
		map.put("msg", "文件上传成功");
		map.put("code", "0000");
		return map;
	}
	

工具类:

java 复制代码
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class Base64FileConverter {
	
	
	  /**
     * 将 Base64 字符串解码并写入文件
     * @param base64String 包含文件数据的 Base64 字符串
     * @param outputFilePath 输出文件的路径
     * @throws IOException 如果文件操作出错
     */
    public static void decodeBase64ToFile(String base64String, String outputFilePath) throws IOException {
        // 检查 Base64 字符串是否包含 MIME 类型前缀(如 data:image/jpeg;base64,)
        String pureBase64 = base64String;
        int commaIndex = base64String.indexOf(',');
        if (commaIndex > 0) {
            pureBase64 = base64String.substring(commaIndex + 1);
        }

        // 解码 Base64 字符串
        byte[] fileData = Base64.getDecoder().decode(pureBase64);

        // 写入文件
        try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
            fos.write(fileData);
            System.out.println("文件已成功写入: " + outputFilePath);
        }
    }

    /**
     * 将文件编码为 Base64 字符串
     * @param filePath 文件路径
     * @return 文件的 Base64 编码字符串
     * @throws IOException 如果文件操作出错
     */
    public static String encodeFileToBase64(String filePath) throws IOException {
        byte[] fileData = Files.readAllBytes(Paths.get(filePath));
        return Base64.getEncoder().encodeToString(fileData);
    }


}

上面就是对文件上传的通过ajax来实现的步骤,希望对你有所帮助

相关推荐
QQ1__8115175153 小时前
Spring boot名城小区物业管理系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·vue.js·spring boot
钛态3 小时前
前端微前端架构:大项目的救命稻草还是自找麻烦?
前端·vue·react·web
一粒黑子3 小时前
【实战解析】阿里开源 PageAgent:纯前端 GUI Agent,一行JS让网页支持自然语言操控
前端·javascript·开源
独角鲸网络安全实验室3 小时前
2026微信小程序抓包全解析:从实操落地到合规风控,解锁前端调试新范式
前端·微信小程序·小程序·抓包·系统代理绕过·https证书严格校验·进程隔离
紫微AI3 小时前
前端文本测量成了卡死一切创新的最后瓶颈,pretext实现突破了
前端·人工智能·typescript
GISer_Jing3 小时前
AI前端(From豆包)
前端·aigc·ai编程
IT枫斗者3 小时前
前端部署后如何判断“页面是不是最新”?一套可落地的版本检测方案(适配 Vite/Vue/React/任意 SPA)
前端·javascript·vue.js·react.js·架构·bug
测试修炼手册3 小时前
[测试技术] 深入理解 JSON Web Token (JWT)
前端·json
AI老李3 小时前
2026 年 Web 前端开发的 8 个趋势!
前端
里欧跑得慢3 小时前
15. Web可访问性最佳实践:让每个用户都能平等访问
前端·css·flutter·web