文件上傳也是常見的功能,趁著周末,用Spring boot來實(shí)現(xiàn)一遍。
前端部分
前端使用jQuery,這部分并不復(fù)雜,jQuery可以讀取表單內(nèi)的文件,這里可以通過formdata對(duì)象來組裝鍵值對(duì),formdata這種方式發(fā)送表單數(shù)據(jù)更為靈活。你可以使用它來組織任意的內(nèi)容,比如使用
1
|
formData.append( "test1" , "hello world" ); |
在kotlin后端就可以使用@RequestParam("test1") greet: String
來取得他的值。
在本例的上傳中,formdata用于裝配上傳表單,就像這樣:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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對(duì)象,在前端連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í)不需要編碼的對(duì)象,就把這個(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è)返回的對(duì)象:
1
|
class UploadResult(val success: Boolean, val message: String, val files: Array<String>) |
•success: 告訴前端是否上傳成功
•message:服務(wù)器端往前端返回的信息,可以包含任意后端想返回的內(nèi)容,比如今天服務(wù)器所在地天氣不好,所以服務(wù)器打算拒絕非管理員的上傳請(qǐng)求。
•files:上傳成功了哪些文件。、
后端的關(guān)鍵代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@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),希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
原文鏈接:http://www.cnblogs.com/asis/p/spring-boot-fileupload-with-jquery.html