使用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來實現的步驟,希望對你有所幫助