SpringMVC 通過ajax 實現(xiàn)文件上傳的步驟
使用form表單在springmvc 項目中上傳文件,文件上傳成功之后往往會跳轉(zhuǎn)到其他的頁面。但是有的時候,文件上傳成功的同時,并不需要進(jì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)文章
Spring?Data?Elasticsearch?5.0.x修改數(shù)據(jù)后無法立即刷新解決方法示例
這篇文章主要為大家介紹了Spring?Data?Elasticsearch?5.0.x修改數(shù)據(jù)后無法立即刷新解決方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
java利用delayedQueue實現(xiàn)本地的延遲隊列
這篇文章主要給大家介紹了java利用delayedQueue實現(xiàn)本地的延遲隊列的相關(guān)資料,文中介紹的非常詳細(xì),相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-04-04
Spring中@Service注解的作用與@Controller和@RestController之間區(qū)別
這篇文章主要介紹了Spring中@Service注解的作用與@Controller和@RestController之間的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-03-03

