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

相关推荐
kgduu8 分钟前
js之错误处理
开发语言·前端·javascript
德莱厄斯9 分钟前
Milkup 技术内幕:一个 Typora 风格的即时渲染 Markdown 编辑器是怎样炼成的
前端·javascript·markdown
Mintopia18 分钟前
架构师的心胸:把分歧装进系统,把人放在方案前
前端·架构
亿元程序员19 分钟前
不是说现在AI很牛吗,怎么连个高光Shader效果都写不好?
前端
孟祥_成都23 分钟前
金三银四,一个面试官连连夸赞的个人网页技术分享
前端·面试·three.js
兆子龙30 分钟前
Vite 插件系统与构建流水线源码解析:从 Rollup 插件到 HMR
前端
代码老中医35 分钟前
Node_modules 比黑洞还重,我们的硬盘到底做错了什么?
前端
兆子龙36 分钟前
Vue 3 响应式系统 Reactivity 源码深度解析:从 ref 到 effect 的完整链路
前端
Smoothcloud_润云39 分钟前
GORM 事务管理与 Repository 模式完整指南
前端·数据库·代码规范
兆子龙39 分钟前
Turborepo 与 Monorepo 任务调度源码解析:从 DAG 到增量构建
前端·架构