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来实现的步骤,希望对你有所帮助

相关推荐
kyriewen24 分钟前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_23332 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
山河木马3 小时前
矩阵专题3-怎么创建投影矩阵(uProjectionMatrix)
javascript·webgl·计算机图形学
天蓝色的鱼鱼4 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷5 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花5 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷5 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜5 小时前
Spring Boot 核心知识点总结
前端
lichenyang4535 小时前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端