文件上传也是常见的功能,趁着周末,用Spring boot来实现一遍。
前端部分
前端使用jQuery,这部分并不复杂,jQuery可以读取表单内的文件,这里可以通过formdata对象来组装键值对,formdata这种方式发送表单数据更为灵活。你可以使用它来组织任意的内容,比如使用
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标签都不需要。
其中关于上面代码的几点解释:
•如果input标签上使用了multiple,那么用户可能选择多个文件,所以再装配formdata的时候,需要上面的each循环。
•contentType: false 设置成false告诉jQuery在header里不要用任何的content type。
•processData: false:告诉jQuery不用讲传输内容编码(因为默认的content type是application/x-/syler/Fun/tree/master/spring-boot-file-upload-with-jquery
最后上一张截图,图片上传成功:
以上所述是小编给大家介绍的使用Spring boot + jQuery上传文件(kotlin),希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!