fileinput给了个maxFileCount参数来限制上传文件数目,但是仍然多图片可以分批量上传,我这里只需要上传一个,所以就修改了一下,如下:
依赖静态资源
jquery
bootstrap的js和css文件
中文需要 zh.js
主题选配themes下js和css
html内容
封面:
js内容
$("#bookimg").fileinput({
'uploadUrl': '/common/upload',
overwriteInitial: false,
maxFileSize: 1500,
showClose: false,
showCaption: false,
showBrowse: false,
initialPreviewAsData: true,
browseOnZoneClick: true,
initialPreview: [
//"/img/profile.jpg"
],
removeLabel: '删除',
removeIcon: '',
removeTitle: 'Cancel or reset changes',
elErrorContainer: '#kv-avatar-errors',
msgErrorClass: 'alert alert-block alert-danger',
defaultPreviewContent: '
Click to select
',layoutTemplates: {main2: '{preview} ' + ' {remove} {browse} {upload}'},
allowedFileExtensions : ['jpg', 'png','bmp','jpeg']
});
$("#bookimg").on("fileuploaded", function (event, data, previewId, index) {
if(data.response.code == 0){
alert('上传成功');
}
});
springboot
Controller层
@PostMapping("/common/upload")
@ResponseBody
public BtResult uploadFile(MultipartFile file) throws Exception
{
try
{
// 上传文件路径
String filePath = Global.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
BtResult btResult= BtResult.success();
btResult.put("fileName", fileName);
btResult.put("url", url);
return btResult;
}
catch (Exception e)
{
return BtResult .error(e.getMessage());
}
}
service层
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
InvalidExtensionException
{
int fileNamelength = file.getOriginalFilename().length();
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
{
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
}
assertAllowed(file, allowedExtension);
String fileName = extractFilename(file);
File desc = getAbsoluteFile(baseDir, fileName);
file.transferTo(desc);
String pathFileName = getPathFileName(baseDir, fileName);
return pathFileName;
}
运行显示,如下:
点击图像选择上传文件,如下:
点击上传,如下:
好了,上传完后,就不能再上传了