ajax+springmvc表单上传文件

多重验证的ajax上传文件是在用户点击选择图片后就把图片异步传给后台,这样可以起到多重验证的目的,更为安全一些,但我考虑到用户会多次选择图片,这样就会异步把选择过的图片都传给后台,从而使服务器多存储一下无用的图片,在这并没有用到多重验证的ajax上传文件,但是符合大家业务需求。

HTML代码:这里用到的是Bootstrap框架

<form class="form-horizontal" id="data_form" enctype="multipart/form-data" 	action="后台路径" method="POST">
                   <div class="form-group">
					<label class="control-label">上传产品图片:</label> <label
						class="btn btn-primary">选择图片 <input type="file"
						style="display: none" class="form-control" name="file"
						onchange="viewImage(this)" />
					</label>
				</div>
          <button type="button" class="btn btn-primary"  onclick="saveData()">提交</button>
</form>

ajax代码:

//保存信息
function saveData() {
	if($("#preview").attr("src") == null || $("#preview").attr("src") == ""){
		toastr.error("图片不能为空!");
		return ;         		
	}
	//获取表单对象
    var bootstrapValidator = $('#data_form').data('bootstrapValidator');
    //手动触发验证
    bootstrapValidator.validate();
    if(bootstrapValidator.isValid()){
    	//表单提交的方法、比如ajax提交
    	//document.forms[0].submit();
    	// 上传设置  
    	var options = {  
       	    // 规定把请求发送到那个URL  
       	    url: "你的url",  
       	    // 请求方式  
       	    type: "post",
       	    // 服务器响应的数据类型  
       	    dataType: "json", 
       	    //成功提交后,是否清除所有表单元素的值
       	    clearForm: true,  
       		//成功提交后,是否重置所有表单元素的值
            resetForm: true,  
       	    // 请求成功时执行的回调函数  
       	    success: function(data, status, xhr) {  
       		    if(data.status==200){
       		    	$('#dataDialog').modal('hide');
       				showData(goPageIndex);
       				toastr.success("信息保存成功!");
       				window.location.reload();
       		    }else if(data.status==2001){
       		    	toastr.error("信息保存失败!"); 
       		    }
       	    }  
        };  
        $("#data_form").ajaxSubmit(options);
    }
}

Controller层代码:

	//保存
	@RequestMapping("/save")
	@ResponseBody
	public Object save(@RequestParam(value = "file", required = false) MultipartFile file,
			TbTask task, HttpServletRequest request, ModelMap model) {
		Result result = new Result();
		try {
			if(task.getId() == null) {
				result =TbTaskService.insert(file,task); 
			} else {
				result =TbTaskService.update(file,task); //修改图片操作,如果不需要修改图片删除这行代码就可以
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(2001);
			result.setMsg("保存失败");
		}
		//return "redirect:/task/taskManage";
		return result;
	}

service层代码:

public Result insert(MultipartFile file, TbTask task){
		Result result = new Result();
		//图片上传
		if (file != null) {
			String image_perfix = FilenameUtils.getExtension(file.getOriginalFilename());//获取图片后缀
			// 上传图片保存的文件名(文章标题+当前时间戳+格式)
			String image_key = "task" + DateUtil.getTimeStamp() + "." + image_perfix;
			// 图片格式判断
			if (CommonUtil.imageType(image_perfix)) {
				// 上传成功返回图片路径
				//String basePath = "D:/ws";
				String basePath = upload_path;
				String filePath = basePath + "/" + image_key;
				String accessPath = access_path+ "/" +image_key;
				File desFile = new File(filePath);
				if(!desFile.getParentFile().exists()){
					desFile.mkdirs();
				}
				try {
					file.transferTo(desFile);
				} catch (IllegalStateException | IOException e) {
					e.printStackTrace();
					result.setStatus(2001);
					result.setMsg("保存失败");
					return result;
				}
				
				task.setState(1);
				task.setRealtimetaskcount(task.getAmounttaskcount());
				task.setCreatetime(DateUtil.getDateTime());
				task.setPicture(image_key);
			} else {
				result.setStatus(2002);
				result.setMsg("上传文件格式不正确");
				return result;
			}
		}			
		TbTaskDao.save(task);
		result.setStatus(200);
		result.setMsg("保存成功");
		return result;
    }

Dao层:

void save(@Param("item")Object obj);

Mapper层:

	<insert id="save" keyProperty="item.id" useGeneratedKeys="true">
		<include refid="sql_save_columns" /> //这里是引用通用判断SQL 
		<include refid="sql_save_values" /> 
	</insert>
    
    <sql id="sql_save_columns">
		insert into tb_task(
		<if test="null != item.picture"> picture</if>
		<if test="null != item.platform">, platForm</if>
		<if test="null != item.storename">, storeName</if>
		<if test="null != item.productname">, productName</if>
		<if test="null != item.price">, price</if>
		<if test="null != item.taskinterval">, taskInterval</if>
		<if test="null != item.refundtype">, refundType</if>
		<if test="null != item.tasktype">, taskType</if>
		<if test="null != item.wangwangask">, wangwangAsk</if>
		<if test="null != item.taskwelfare">, taskWelfare</if>
		<if test="null != item.realtimetaskcount">, realTimeTaskCount</if>
		<if test="null != item.amounttaskcount">, amountTaskCount</if>
		<if test="null != item.state">, state</if>
		<if test="null != item.searchkey">, searchKey</if>
		<if test="null != item.searchkeytime">, searchKeyTime</if>
		<if test="null != item.partfourbrowse">, partFourBrowse</if>
		<if test="null != item.partfourbrowsetime">, partFourBrowseTime</if>
		<if test="null != item.browseproduct">, browseProduct</if>
		<if test="null != item.browseproducttime">, browseProductTime</if>
		<if test="null != item.customer">, customer</if>
		<if test="null != item.customertime">, customerTime</if>
		<if test="null != item.paymenttime">, paymentTime</if>
		<if test="null != item.payment">, payment</if>
		<if test="null != item.createtime">, createTime</if>
		<if test="null != item.store">, store</if>
		) values
	</sql>

    <sql id="sql_save_values">
		(
		<if test="null != item.picture"> #{item.picture}</if>
		<if test="null != item.platform">, #{item.platform}</if>
		<if test="null != item.storename">, #{item.storename}</if>
		<if test="null != item.productname">, #{item.productname}</if>
		<if test="null != item.price">, #{item.price}</if>
		<if test="null != item.taskinterval">, #{item.taskinterval}</if>
		<if test="null != item.refundtype">, #{item.refundtype}</if>
		<if test="null != item.tasktype">, #{item.tasktype}</if>
		<if test="null != item.wangwangask">, #{item.wangwangask}</if>
		<if test="null != item.taskwelfare">, #{item.taskwelfare}</if>
		<if test="null != item.realtimetaskcount">, #{item.realtimetaskcount}</if>
		<if test="null != item.amounttaskcount">, #{item.amounttaskcount}</if>
		<if test="null != item.state">, #{item.state}</if>
		<if test="null != item.searchkey">, #{item.searchkey}</if>
		<if test="null != item.searchkeytime">, #{item.searchkeytime}</if>
		<if test="null != item.partfourbrowse">, #{item.partfourbrowse}</if>
		<if test="null != item.partfourbrowsetime">, #{item.partfourbrowsetime}</if>
		<if test="null != item.browseproduct">, #{item.browseproduct}</if>
		<if test="null != item.browseproducttime">, #{item.browseproducttime}</if>
		<if test="null != item.customer">, #{item.customer}</if>
		<if test="null != item.customertime">, #{item.customertime}</if>
		<if test="null != item.paymenttime">, #{item.paymenttime}</if>
		<if test="null != item.payment">, #{item.payment}</if>
		<if test="null != item.createtime">, #{item.createtime}</if>
		<if test="null != item.store">, #{item.store}</if>
		)
	</sql>

最后

在这里插入图片描述

来呀,加微信好友一起讨论技术呀…

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值