SpringBoot+layui上传图片(图片流)的方式传到数据库

这中方式是能够选择多组图片进行上传,并且是异步的形式,虽然选择的多个图片,但是却是一个图片一个图片存的,所以后台方法中写的是存一个图片的方法

HTML

 

 

JS

upPhoto:function () {
			var me=this;
			 var id=$("#reportId").val();
			var multiple_images = [];
			layui.use('upload', function () {
				var upload = layui.upload;
				upload.render({
					elem: '#multiple_img_upload'
					,url: __ctx+'/platform/data/uemiReport/upPhoto?id='+id
					,multiple: true
					,before: function(obj){
						//预读本地文件示例,不支持ie8
						obj.preview(function(index, file, result){
							$('#div-slide_show').append(''+ file.name
								+'')
						});
					}
					,done: function(res){
						//如果上传成功
						if (res.result==1) {
							//追加图片成功追加文件名至图片容器
							multiple_images.push(res.cause);
							$('.multiple_show_img').val(multiple_images);
						}else {
							//提示信息
							DialogUtil.alert(res.message);
						}
					}
				});

			});
		},

Controller

@RequestMapping("upPhoto")
	public void upPhoto(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
		ResultMessage message=null;
		try{
			Long reportId = RequestUtil.getLong(request, "id");
			MultipartFile file = request.getFile("file");
			upPhotoService.savePhoto(file,reportId);
			String fileName = file.getOriginalFilename();
			File dest = new File(photoPath + fileName);
			file.transferTo(dest);
			message=new ResultMessage(ResultMessage.Success, "上传成功");
			message.setCause(photoPath + fileName);
		}catch(Exception e){
			logger.debug(e.getMessage());
			message=new ResultMessage(ResultMessage.Fail, "上传失败",e.getMessage());
		}
		writeResultMessage(response.getWriter(), message);
	}

service:

 @Override
	public void savePhoto(MultipartFile file,Long reportId) throws Exception {
		try{
			String fileName = file.getOriginalFilename();
			byte[] bytes = file.getBytes();
			UpPhoto upPhoto = new UpPhoto();
			//得到文件名
			upPhoto.setFileName(fileName.split("\\.")[0]);
			long photoId = UniqueIdUtil.genId();
			upPhoto.setId(photoId);
			//得到文件类型
			upPhoto.setFormat(fileName.split("\\.")[1]);
			//存入图片流
			upPhoto.setFileStream(bytes);
			add(upPhoto);

			ReportPhotoRel reportPhotoRel = new ReportPhotoRel();
			reportPhotoRel.setId(UniqueIdUtil.genId());
			reportPhotoRel.setPhotoId(photoId);
			reportPhotoRel.setReportId(reportId);
			reportPhotoRelService.add(reportPhotoRel);
		}catch(Exception e){
			logger.debug(e.getMessage());
		}
	}

 

你可能感兴趣的:(javaweb程序设计)