jquery 获取文件的绝对路径path和名称name将其组装到flilearry里面然后传到java后台Controller
在前端使用jQuery获取文件的绝对路径和名称,然后将其组装到一个数组中,并传递到后台的Java Controller,可以按照以下步骤进行操作:
- 在前端页面中使用input标签创建一个文件上传的表单控件,并给它一个id,例如:
<input type="file" id="fileInput" multiple>
- 使用jQuery监听文件选择事件,并获取选择的文件的绝对路径和名称,将其组装到一个数组中,例如:
$(document).ready(function() {
$('#fileInput').change(function() {
var files = $(this)[0].files;
var fileArray = [];
for (var i = 0; i < files.length; i++) {
var file = {
path: files[i].webkitRelativePath, // 获取文件的绝对路径
name: files[i].name // 获取文件的名称
};
fileArray.push(file);
}
// 将fileArray传递到后台Controller
$.ajax({
url: '/your-controller-url',
type: 'POST',
data: JSON.stringify(fileArray),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(response) {
// 处理成功响应
},
error: function(xhr, status, error) {
// 处理错误响应
}
});
});
});
- 在后台的Java Controller中接收传递过来的文件路径和名称数组,例如:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class YourController {
@PostMapping("/your-controller-url")
public void handleFiles(@RequestBody List<File> fileArray) {
// 处理接收到的文件路径和名称数组
}
}
请注意,上述代码中的 /your-controller-url 需要根据实际情况修改为后台Controller的URL。另外,确保在前端页面中引入了jQuery库
原文地址: https://www.cveoy.top/t/topic/ioTU 著作权归作者所有。请勿转载和采集!