?单个文件
<div style="display: none;">
<input id="file" type="file" onchange="doupload" accept="image/jpeg,image/jpg,image/png,image/svg" name="file"/>
</div>
<button onclick="pickFile">Upload<button>
function pickFile(){
$('#file').click();
}
function doupload(){
let fileElem = $('#file');
let file = fileElem.files[0];
if (undefined == file || null == file)
return;
let formData = new FormData();
formData.append("file", file);
formData.append("personId", this.person.id);
$.ajax({
type: 'post',
headers:{
'Authorization': 'token'
},
url: "https://xxxx/upload/mutiple",
data: formData,
cache: false,
processData: false,
contentType: false,
}).success(function (data) {
console.log(data);
}).error(function () {
alert("上传失败");
});
}
java后台:
@PostMapping("/single")
@ResponseBody
public Result doUpload(@RequestParam("file") MultipartFile file,
@RequestParam("personId") String personId){
}
多个文件
<div style="display: none;">
<input id="file" type="file" multiple="multiple" onchange="doupload" name="file"/>
</div>
<button onclick="pickFile">Upload<button>
function pickFile(){
$('#file').click();
}
function doupload(){
let files = $('#file').files;
if(undefined != files && files.length > 0){
let formData = new FormData();
files.forEach(function(f){
formData.append("files",f);
})
formData.append("personId", this.person.id);
$.ajax({
url: "https://xxxx/upload/mutiple",
});
}
}
java后台:
@PostMapping("/mutiple")
@ResponseBody
public Result doUploadMutiple(@RequestParam("files") MultipartFile[] files,
@RequestParam("personId") String personId){
if(null == files || 0 == files.length)
return Result.failed("没有文件");
for(MultipartFile file : files){
byte[] byteData = ByteStreams.toByteArray(file.getInputStream());
// push to the cloud server
}
}
|