使用form表单在springmvc 项目中上传文件,文件上传成功之后往往会跳转到其他的页面。但是有的时候,文件上传成功的同时,并不需要进行页面的跳转,可以通过ajax来实现文件的上传
下面我们来看看如何来实现:
方式1:前台从dom对象中获取到文件,并且将文件解析为Blob ,我们来看看页面代码:
<input type="file" class="inputPic" />
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); // poxhr.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>
后台:
@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,然后上传到后台:
前端代码:
<input type="file" class="inputPic" />
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); // poxhr.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("图片上传成功");}}}});
后端代码:
@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;}
工具类:
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来实现的步骤,希望对你有所帮助