spring boot html上传文件,springboot集成bootstrap fileinput实现单个文件上传 互联网技术圈 互联网技术圈...

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: 'springboot集成bootstrap fileinput实现单个文件上传

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;

}

运行显示,如下:

dfa6622f88aa8f647375e19c265f9252.png

点击图像选择上传文件,如下:

024332af7d4ac45ba63c30c1bfbd6b40.png

点击上传,如下:

b2e73ca1b3b425f3b6b6a3076d57e71d.png

好了,上传完后,就不能再上传了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值