java+web上传图片保存到数据库

1.上传图片:html代码示例。

<div class="form-group  col-sm-12">
    <label class="col-sm-2 control-label no-padding-right"><span class="ytRequired"></span>头像:</label>
    <div class="col-sm-4">
        <div class="col-sm-12 upload-content" id="upImageDiv">
            <input type="file" id="uploadInput" accept="image/gif,image/jpeg,image/x-png" class="fileInput" />
            <a href="javascript:void(0)" class="selectImage">上传图片</a>
        </div>
        <div class="imageBox" id="imageBox" style="margin-top: 10%;">
        </div>
    </div>
</div>

2.上传图片:初始页面要加入代码,uploadInput是上面的input框的id,imageBox,是上面要显示图片的div。

<script type="text/javascript">
	uploadImageInit("uploadInput", "imageBox");
</script>

上传图片封装的js文件uploadLocalImage.js。

/**
 * 初始化图片(图片上传封装控件)
 * @author tyg
 */

/**
 * 初始化上传图片控件(只能单张图片)
 * @param inputId		input框点击上传的按钮id,可空,默认:uploadInput
 * @param boxId			显示区域的id,可空,默认:imageBox
 * @returns
 */
function uploadImageInit(inputId, boxId){
	if(inputId == undefined || inputId == null){
		inputId = "uploadInput";
	}
	if(boxId == undefined || boxId == null){
		boxId = "imageBox";
	}
	$("#"+inputId).change(function(){
		var reader = new FileReader();
		var file = document.getElementById(inputId).files[0];
		if(file.size/1024/1024 > 10){
			$.success("上传图片不能大于10M!");
		}
		reader.readAsDataURL(file);
		reader.onload = function(e) {
			var imgHtml="";
			imgHtml+="<div class='image_item' style='width:160px;height:160px;'>";
			imgHtml+="<img src='"+this.result+"' alt='' style='display: block;'/>";
			imgHtml+="<span class='delete' onclick='deleteImageItem(this)'></span>";
			imgHtml+="</div>";
			$("#" + boxId).html(imgHtml);
		}
	});
}
/**
 * 显示图片,一般用于修改页面,将之前的图片显示出来(只能单张)
 * @param boxId	显示区域的id,可空,默认:imageBox
 * @param url	图片地址
 * @returns
 */
function showImage(boxId, url){
	if(boxId == undefined || boxId == null){
		boxId = "imageBox";
	}
  	var imgHtml="";
  	imgHtml+="<div class='image_item' style='width:160px;height:160px;'>";
  	imgHtml+="<img src='"+url+"' alt='' style='display: block;'/>";
  	imgHtml+="<span class='delete' onclick='deleteImageItem(this)'></span>";
  	imgHtml+="</div>";
  	$("#" + boxId).html(imgHtml);
}

/**
 * 显示图片,一般用于修改页面,将之前的图片显示出来(可以多张)
 * @param boxId	显示区域的id,可空,默认:imageBox
 * @param url	图片地址
 * @returns
 */
function showImages(boxId, url){
	if(boxId == undefined || boxId == null){
		boxId = "imageBox";
	}
	var imgHtml=$("#" + boxId).html();
	imgHtml+="<div class='image_item' style='width:160px;height:160px; margin-left:5px; float: left'>";
	imgHtml+="<img src='"+url+"' alt='' style='display: block;'/>";
	imgHtml+="<span class='delete' data-id='"+url+"' onclick='deleteImageItem(this)'></span>";
	imgHtml+="</div>";
	$("#" + boxId).html(imgHtml);
}
/**
 * 获取单张图片文件
 * @param inputId	input框的id
 * @returns	返回的是文件
 */
function getImageUrl(inputId){
	return document.getElementById(inputId).files[0];
}
// 删除图片
function deleteImageItem(obj){
    var id = $(obj).attr("data-id");
    photo.deletePhoto(id);
  	$(obj).parent().remove();
};

3.上传图片:获取图片文件,返回值是一个文件,js代码示例。

var file = getImageUrl("uploadInput");

4.上传图片:上传文件必须使用FormData。

var formData = new FormData();
formData.append('phone', params.phone);
formData.append('name', params.name);
formData.append('file', file);
// 上传图片的请求
$.processDataImg(url, formData, function(result) {
	if (result.state == 200) {
		$.success('操作成功!');
		user.backList();
	} else {
		$.error(result.message);
	}
})

注意:发起请求时需要加入:

contentType: false,
processData: false,
mimeType: "multipart/form-data",

5.上传图片:后台接收要使用:@RequestParam(required = false) MultipartFile file,required=false是为了避免为空出现异常,并且后台要在spring的配置文件配置如下代码。

<!-- SpringMVC默认是关闭fileupload功能的,开启该能够并验证文件上传 -->
<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="20000000"/>
    <property name="maxInMemorySize" value="1024000" />
</bean>
@RequestMapping(value = "/user/addUser", method = RequestMethod.POST)
public Object addUser(UserAddVO user, @RequestParam(required = false) MultipartFile file) throws BusinessException {
	user.setFileHeadImg(file);
	userI.addUser(user);
	return ResultUtil.success();
}

/**
 * 读取图片
 * @param file	文件
 * @param size	上传图片大小(单位M)
 * @return
 * @throws BusinessException
 * @return byte[]
 * @author tyg
 * @date   2019年3月19日上午12:33:47
 */
public static byte[] getImgByte(MultipartFile file, Long size) throws BusinessException {
	if (file != null) {
		try {
			size = size == null ? 5120000L : size * 1024L * 1024L;
			Assert.isTrue(file.getSize() > size.longValue(), "上传图片不能超过"+(size / 1024L / 1024L)+"M!");
			InputStream stream = file.getInputStream();
			byte[] pictureData = new byte[(int) file.getSize()];  
			stream.read(pictureData);
			return pictureData;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("读取文件失败!");
		}
		
	}
	return null;
}

6.上传图片:后台将file转为byte[],就可以直接存到数据库了数据的类型要设置为blob或者是longblob。

byte[] fileByte = ImageUtil.getImgByte(file,null);

7.显示图片:

showImage("imageBox", "/img/showUserHeadImage?_"+new Date().getTime()+"&id="+id);
/**
 * 响应图片流
 * @param response
 * @param imgData
 * @return void
 * @author tyg
 * @date   2019年3月15日上午10:49:55
 */
public static void writeImg(HttpServletResponse response, byte[] imgData) {
	response.setContentType("image/jpeg");
	ServletOutputStream outputStream = null;
	try {
		outputStream = response.getOutputStream();
		outputStream.write(imgData);
		outputStream.flush();
	} catch (IOException e) {
		e.printStackTrace();
		logger.info("读取文件失败!");
	} finally {
		closeIo(outputStream);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_26365837/article/details/89228985
今日推荐