SpringMVC 通過ajax 實現(xiàn)文件上傳的步驟
使用form表單在springmvc 項目中上傳文件,文件上傳成功之后往往會跳轉(zhuǎn)到其他的頁面。但是有的時候,文件上傳成功的同時,并不需要進行頁面的跳轉(zhuǎn),可以通過ajax來實現(xiàn)文件的上傳
下面我們來看看如何來實現(xiàn):
方式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); // po xhr.upload.onloadstart = function() {// 上傳開始執(zhí)行方法 ot = new Date().getTime(); // 設(shè)置上傳開始時間 oloaded = 0;// 設(shè)置上傳開始時,以上傳的文件大小為0 }; xhr.send(form); // 開始上傳,發(fā)送form數(shù)據(jù) 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:前端將文件轉(zhuǎn)換為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); // po xhr.upload.onloadstart = function() {// 上傳開始執(zhí)行方法 ot = new Date().getTime(); // 設(shè)置上傳開始時間 oloaded = 0;// 設(shè)置上傳開始時,以上傳的文件大小為0 }; xhr.send(form); // 開始上傳,發(fā)送form數(shù)據(jù) 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 包含文件數(shù)據(jù)的 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來實現(xiàn)的步驟,希望對你有所幫助
到此這篇關(guān)于SpringMVC 通過ajax 實現(xiàn)文件的上傳的文章就介紹到這了,更多相關(guān)SpringMVC ajax 文件上傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中 % 與Math.floorMod() 區(qū)別詳解
這篇文章主要介紹了Java中 % 與Math.floorMod() 區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08使用Spring Boot實現(xiàn)操作數(shù)據(jù)庫的接口的過程
本文給大家分享使用Spring Boot實現(xiàn)操作數(shù)據(jù)庫的接口的過程,包括springboot原理解析及實例代碼詳解,感興趣的朋友跟隨小編一起看看吧2021-07-07詳解Java利用同步塊synchronized()保證并發(fā)安全
這篇文章主要介紹了Java利用同步塊synchronized()保證并發(fā)安全,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03SpringBoot參數(shù)校驗:@Valid與@Validated使用詳解
這篇文章主要介紹了SpringBoot參數(shù)校驗:@Valid與@Validated使用詳解,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03Java JFinal框架中實現(xiàn)添加定時任務(wù)功能詳解
這篇文章主要為大家詳細介紹了如何在JFinal框架項目中添加定時任務(wù)的功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-02-02Springboot+AOP實現(xiàn)返回數(shù)據(jù)提示語國際化的示例代碼
這篇文章主要介紹了Springboot+AOP實現(xiàn)返回數(shù)據(jù)提示語國際化的示例代碼,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-07-07Java實現(xiàn)MapStruct對象轉(zhuǎn)換的示例代碼
本文主要介紹了MapStruct在Java中的對象轉(zhuǎn)換使用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12