Spring Boot 利用WebUploader进行文件上传功能

2025-05-29 0 101

web uploader简介

webuploader是由baidu webfe(fex)团队开发的一个简单的以html5为主,flash为辅的现代文件上传组件。在现代的浏览器里面能充分发挥html5的优势,同时又不摒弃主流ie浏览器,沿用原来的flash运行时,兼容ie6+,ios 6+, android 4+。两套运行时,同样的调用方式,可供用户任意选用。采用大文件分片并发上传,极大的提高了文件上传效率。

我们这里使用官网的一个例子来实现我们个人头像的上传。

我们的重点是在spring boot项目中利用webuploader如何进行文件上传,所以直接实现一个简单的功能,仅供参考。

下面是一个从官网下载来的示例:带剪裁的图片上传功能。

Spring Boot 利用WebUploader进行文件上传功能

我们利用示例来改造项目中的个人头像上传。

效果看起来是这样的:

Spring Boot 利用WebUploader进行文件上传功能

Spring Boot 利用WebUploader进行文件上传功能

首先我们来改造我们的webuploader示例代码。

以下都是我项目中的部分代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256
(function( factory ) {

if ( !window.jquery ) {

alert('jquery is required.')

}

jquery(function() {

factory.call( null, jquery );

});

})

(function( $ ) {

// -----------------------------------------------------

// ------------ start ----------------------------------

// -----------------------------------------------------

// ---------------------------------

// --------- uploader -------------

// ---------------------------------

var uploader = (function() {

// -------setting-------

// 如果使用原始大小,超大的图片可能会出现 croper ui 卡顿,所以这里建议先缩小后再crop.

var frame_width = 1600;

var _ = webuploader;

var uploader = _.uploader;

var uploadercontainer = $('.uploader-container');

var uploader, file;

if ( !uploader.support() ) {

alert( 'web uploader 不支持您的浏览器!');

throw new error( 'webuploader does not support the browser you are using.' );

}

// hook,

// 在文件开始上传前进行裁剪。

uploader.register({

'before-send-file': 'cropimage'

}, {

cropimage: function( file ) {

var data = file._cropdata,

image, deferred;

file = this.request( 'get-file', file );

deferred = _.deferred();

image = new _.lib.image();

deferred.always(function() {

image.destroy();

image = null;

});

image.once( 'error', deferred.reject );

image.once( 'load', function() {

image.crop( data.x, data.y, data.width, data.height, data.scale );

});

image.once( 'complete', function() {

var blob, size;

// 移动端 uc / qq 浏览器的无图模式下

// ctx.getimagedata 处理大图的时候会报 exception

// index_size_err: dom exception 1

try {

blob = image.getasblob();

size = file.size;

file.source = blob;

file.size = blob.size;

file.trigger( 'resize', blob.size, size );

deferred.resolve();

} catch ( e ) {

console.log( e );

// 出错了直接继续,让其上传原始图片

deferred.resolve();

}

});

file._info && image.info( file._info );

file._meta && image.meta( file._meta );

image.loadfromblob( file.source );

return deferred.promise();

}

});

return {

init: function( selectcb ) {

uploader = new uploader({

pick: {

id: '#filepicker',

multiple: false

},

// 设置用什么方式去生成缩略图。

thumb: {

quality: 70,

// 不允许放大

allowmagnify: false,

// 是否采用裁剪模式。如果采用这样可以避免空白内容。

crop: false

},

// 禁掉分块传输,默认是开起的。

chunked: false,

// 禁掉上传前压缩功能,因为会手动裁剪。

compress: false,

// filesinglesizelimit: 2 * 1024 * 1024,

server: 'studentimgfileupload',

swf: $.trim($("#base_url").val()) + '/static/webuploader/uploader.swf',

filenumlimit: 1,

// 只允许选择图片文件。

accept: {

title: 'images',

// extensions: 'gif,jpg,jpeg,bmp,png',

// mimetypes: 'image/*'

extensions: 'jpg,jpeg,png',

//解决webuploader chrome 点击上传文件选择框会延迟几秒才会显示 反应很慢

mimetypes: 'image/jpg,image/jpeg,image/png' //修改这行

}

//formdata: {"authorization": localstorage.token}, //额外参数传递,可以没有

// chunked: true, //分片

// chunksize: 10 * 1024 * 1024, //分片大小指定

// threads:1, //线程数量

// disableglobaldnd: true //禁用拖拽

// onerror: function() {

// var args = [].slice.call(arguments, 0);

// alert(args.join('\\n'));

// }

});

uploader.on('filequeued', function( _file ) {

file = _file;

uploader.makethumb( file, function( error, src ) {

if ( error ) {

alert('不能预览');

return;

}

selectcb( src );

}, frame_width, 1 ); // 注意这里的 height 值是 1,被当成了 100% 使用。

});

/**

* 验证文件格式以及文件大小

*/

uploader.on("error", function (type) {

if (type == "q_type_denied") {

showinfo("请上传jpg、jepg、png、格式文件");

}

});

// 文件上传成功,给item添加成功class, 用样式标记上传成功。

uploader.on( 'uploadsuccess', function( file ) {

showinfo("上传成功");

});

// 文件上传失败,显示上传出错。

uploader.on( 'uploaderror', function( file ) {

showinfo("上传失败");

});

},

crop: function( data ) {

var scale = croper.getimagesize().width / file._info.width;

data.scale = scale;

file._cropdata = {

x: data.x1,

y: data.y1,

width: data.width,

height: data.height,

scale: data.scale

};

},

upload: function() {

uploader.upload();

}

}

})();

// ---------------------------------

// --------- crpper ---------------

// ---------------------------------

var croper = (function() {

var container = $('.cropper-wraper');

var $image = container.find('.img-container img');

var btn = $('.upload-btn');

var isbase64supported, callback;

$image.cropper({

aspectratio: 4 / 4,

preview: ".img-preview",

done: function(data) {

// console.log(data);

}

});

function srcwrap( src, cb ) {

// we need to check this at the first time.

if (typeof isbase64supported === 'undefined') {

(function() {

var data = new image();

var support = true;

data.onload = data.onerror = function() {

if( this.width != 1 || this.height != 1 ) {

support = false;

}

}

data.src = src;

isbase64supported = support;

})();

}

if ( isbase64supported ) {

cb( src );

} else {

// otherwise we need server support.

// convert base64 to a file.

// $.ajax('', {

// method: 'post',

// data: src,

// datatype:'json'

// }).done(function( response ) {

// if (response.result) {

// cb( response.result );

// } else {

// alert("预览出错");

// }

// });

}

}

btn.on('click', function() {

callback && callback($image.cropper("getdata"));

return false;

});

return {

setsource: function( src ) {

// 处理 base64 不支持的情况。

// 一般出现在 ie6-ie8

srcwrap( src, function( src ) {

$image.cropper("setimgsrc", src);

});

container.removeclass('webuploader-element-invisible');

return this;

},

getimagesize: function() {

var img = $image.get(0);

return {

width: img.naturalwidth,

height: img.naturalheight

}

},

setcallback: function( cb ) {

callback = cb;

return this;

},

disable: function() {

$image.cropper("disable");

return this;

},

enable: function() {

$image.cropper("enable");

return this;

}

}

})();

// ------------------------------

// -----------logic--------------

// ------------------------------

var container = $('.uploader-container');

uploader.init(function( src ) {

croper.setsource( src );

// 隐藏选择按钮。

container.addclass('webuploader-element-invisible');

// 当用户选择上传的时候,开始上传。

croper.setcallback(function( data ) {

uploader.crop(data);

uploader.upload();

});

});

// -----------------------------------------------------

// ------------ end ------------------------------------

// -----------------------------------------------------

});

还有页面的部分代码:

下面是controller部分的代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45
@requestmapping(value="/student/studentimgfileupload", method=requestmethod.post)

@responsebody

string studentimgfileupload(@requestparam multipartfile file, httpservletrequest request){

logger.info("学生头像上传....")

//获取文件名

string originalfilename = file.getoriginalfilename()

logger.info("上传文件名:" + originalfilename)

string realpath = request.getservletcontext().getrealpath("/public/student/")

string uploadfilename = system.currenttimemillis()+"_"+ originalfilename

logger.info("获取上传路径:" + realpath + ", 上传的真实文件名:" + uploadfilename)

boolean flag = true

//合并文件

randomaccessfile rafile = null

bufferedinputstream inputstream = null

try{

file dirfile = new file(realpath, uploadfilename)

//以读写的方式打开目标文件

rafile = new randomaccessfile(dirfile, "rw")

rafile.seek(rafile.length())

inputstream = new bufferedinputstream(file.getinputstream())

byte[] buf = new byte[1024]

int length = 0

while ((length = inputstream.read(buf)) != -1) {

rafile.write(buf, 0, length)

}

}catch(exception e){

flag = false

logger.info("上传出错:" + e.getmessage())

throw new ioexception(e.getmessage())

}finally{

try {

if (inputstream != null) {

inputstream.close()

}

if (rafile != null) {

rafile.close()

}

}catch(exception e){

flag = false

logger.info("上传出错:" + e.getmessage())

throw new ioexception(e.getmessage())

}

}

}

这样就简单实现了在spring boot项目中使用webuploader进行文件上传的功能。

总结

以上所述是小编给大家介绍的spring boot 利用webuploader进行文件上传功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:http://blog.csdn.net/cckevincyh/article/details/79646321

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring Boot 利用WebUploader进行文件上传功能 https://www.kuaiidc.com/112472.html

相关文章

发表评论
暂无评论