使用Spring boot + jQuery上傳文件(kotlin)功能實(shí)例詳解
文件上傳也是常見的功能,趁著周末,用Spring boot來實(shí)現(xiàn)一遍。
前端部分
前端使用jQuery,這部分并不復(fù)雜,jQuery可以讀取表單內(nèi)的文件,這里可以通過formdata對象來組裝鍵值對,formdata這種方式發(fā)送表單數(shù)據(jù)更為靈活。你可以使用它來組織任意的內(nèi)容,比如使用
formData.append("test1","hello world");
在kotlin后端就可以使用@RequestParam("test1") greet: String來取得他的值。
在本例的上傳中,formdata用于裝配上傳表單,就像這樣:
function uploadfile() {
var formData = new FormData();
$.each($("input[type='file']")[0].files, function (i, file) {
formData.append('upload-file', file);
});
$.ajax({
url: "/upload",
method: "post",
data: formData,
processData: false,
contentType: false
}).done(function (res) {
if (res.success) {
$("#message").text(res.message + res.files);
$("#message").addClass("green")
$("#message").removeClass("red")
} else {
$("#message").text("cannot upload files, reason: " + res.message)
$("#message").addClass("red")
$("#message").removeClass("green")
}
})
.fail(function (res) {
})
}
使用FormData對象,在前端連form標(biāo)簽都不需要。
其中關(guān)于上面代碼的幾點(diǎn)解釋:
•如果input標(biāo)簽上使用了multiple,那么用戶可能選擇多個(gè)文件,所以再裝配formdata的時(shí)候,需要上面的each循環(huán)。
•contentType: false 設(shè)置成false告訴jQuery在header里不要用任何的content type。
•processData: false:告訴jQuery不用講傳輸內(nèi)容編碼(因?yàn)槟J(rèn)的content type是application/x-www-form-urlencoded)。如我們要發(fā)送DOM或確實(shí)不需要編碼的對象,就把這個(gè)參數(shù)設(shè)成false。
注意:
•如果不將contentType設(shè)置成false,kotlin后端會(huì)報(bào)異常
Current request is not a multipart request
•如果沒有將processData設(shè)成false,javascript會(huì)報(bào)錯(cuò):
Uncaught TypeError: Illegal invocation
•如果要上傳多個(gè)文件,在input標(biāo)簽上設(shè)置multiple屬性。
后端部分
后端準(zhǔn)備在上傳完成后,給前端回復(fù)一個(gè)成功或失敗的信息,為此,創(chuàng)建一個(gè)返回的對象:
class UploadResult(val success: Boolean, val message: String, val files: Array<String>)
•success: 告訴前端是否上傳成功
•message:服務(wù)器端往前端返回的信息,可以包含任意后端想返回的內(nèi)容,比如今天服務(wù)器所在地天氣不好,所以服務(wù)器打算拒絕非管理員的上傳請求。
•files:上傳成功了哪些文件。、
后端的關(guān)鍵代碼:
@ResponseBody
@PostMapping("upload")
fun upload(@RequestPart("upload-file") uploadfile: Array<MultipartFile>): UploadResult {
if (uploadfile.count() == 0) return UploadResult(false, "the uploading file is not detected.", arrayOf())
val dir = env.getProperty("com._1b2m.defaultuploaddir")
val f: File = File(dir)
if (!f.exists()) {
f.mkdirs()
}
for (file in uploadfile) {
val fileName = file.originalFilename;
val filepath: String = Paths.get(dir, fileName).toString()
val stream: BufferedOutputStream = BufferedOutputStream(FileOutputStream(File(filepath)))
stream.write(file.bytes)
stream.close()
}
return UploadResult(true, "successfully uploaded your file(s). ", uploadfile.map { it.originalFilename }.toTypedArray())
}
注意:
在kotlin中的RequestPart("upload-file”),和前端的formData.append('upload-file', file)要保持一致,我這里用的變量叫upload-file,如果不一致,后端就沒有取到數(shù)據(jù)了。
本文涉及到的源代碼:https://github.com/syler/Fun/tree/master/spring-boot-file-upload-with-jquery
最后上一張截圖,圖片上傳成功:

以上所述是小編給大家介紹的使用Spring boot + jQuery上傳文件(kotlin),希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
- jquery+ajaxform+springboot控件實(shí)現(xiàn)數(shù)據(jù)更新功能
- Spring shiro + bootstrap + jquery.validate 實(shí)現(xiàn)登錄、注冊功能
- 玩轉(zhuǎn)spring boot 結(jié)合jQuery和AngularJs(3)
- Spring Boot 中application.yml與bootstrap.yml的區(qū)別
- spring boot+thymeleaf+bootstrap實(shí)現(xiàn)后臺管理系統(tǒng)界面
- AJAX +SpringMVC 實(shí)現(xiàn)bootstrap模態(tài)框的分頁查詢功能
- 基于SpringMVC+Bootstrap+DataTables實(shí)現(xiàn)表格服務(wù)端分頁、模糊查詢
- springboot整合jquery和bootstrap框架過程圖解
相關(guān)文章
idea全局搜索快捷鍵超詳細(xì)總結(jié)(推薦!)
在實(shí)際開發(fā)中項(xiàng)目會(huì)非常多,如何在項(xiàng)目中快速定位,你說需要找到的類或方法,可以利用idea的全局搜索功能,下面這篇文章主要給大家分享介紹了關(guān)于idea全局搜索快捷鍵超詳細(xì)總結(jié)的相關(guān)資料,需要的朋友可以參考下2023-01-01
Java實(shí)現(xiàn)經(jīng)典游戲Flappy Bird的示例代碼
Flappy?Bird是13年紅極一時(shí)的小游戲,即摁上鍵控制鳥的位置穿過管道間的縫隙。本文將用Java語言實(shí)現(xiàn)這一經(jīng)典的游戲,需要的可以參考一下2022-02-02
Java實(shí)現(xiàn)判斷瀏覽器版本與類型簡單代碼示例
這篇文章主要介紹了Java實(shí)現(xiàn)判斷瀏覽器版本與類型簡單代碼示例,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
Spring Boot使用FastJson解析JSON數(shù)據(jù)的方法
本篇文章主要介紹了Spring Boot使用FastJson解析JSON數(shù)據(jù)的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02

