如何使用ajax直接上传文件到服务器中或者本地磁盘中

这几周在做项目的过程中遇到许多问题,这里呢将其中的直接使用ajax做上传文件的问题在这里记录分享一下,当时是用的form表单直接提交,但是这样会报一个post方法或者get方法不支持的错误,或者又是报一个找不到上传文件的参数值的错误,到最后查了好多资料才解决了这个问题,在这里总结:
jsp页面代码如下:
先是有一个上传图片文件的表单,设置id="fileUp"方便在ajax代码中取得参数值,id="stu_pic"是将选择好的图片进行一个及时展示;

<div class="form-group">
  <label class="col-xs-8" for="example-file-input">商品图片:</label>
  <div class="col-xs-8">
    <input type="file" class="btn_file" id="fileUp" name="fileUp" >
    <img id="stu_pic" width="50" height="50">
  </div>
</div>

然后及时ajax响应后台的的代码,这里需要注意的是需要将获取到的图片文件的值转换为formData对象值,要不然后台会无法得到参数,crowd_file就是ajax传递给后台的图片文件的参数;

<script type="text/javascript">
//选择好图片之后及时显示图片
$(document).off('change','fileUp').on('change','#fileUp',function(){
	$('#stu_pic').attr('src',URL.createObjectURL($(this)[0].files[0]));
});
//上传图片方法
 $(".btn_file").on("change",function() {
	//alert("进入方法");
   	 var crowd_file = $('#fileUp')[0].files[0];
   	 var formData = new FormData();
   	 formData.append("crowd_file",$('#fileUp')[0].files[0]);//将获取到的图片文件值保存到formData对象中,是以键值对的形式保存的,crowd_file就是键,$('#fileUp')[0].files[0]就是值
   	 //alert(crowd_file);
   	$.ajax({		
   	  url:'${ctx}/uploadFile',//后台controller的请求路径
   	  type:'post',
   	  dataType: "json",
   	  data: formData,
         async: false,
         cache: false,
         contentType: false,
         processData: false,
 	  	success:function(data){
   		  if(data.result>0){//传递一个json数据json数据的值大于0就表示上传成功,否则上传失败
       		   alert("上传成功"); 
       	   }
       	   else{
				alert("上传失败");
       	   }
   	  }
   	});
   });	 
</script>

接下来就是后台controller中的代码:

//上传商品图片的请求
@RequestMapping(value="/uploadFile",method = RequestMethod.POST)
@ResponseBody
public Object addProduct(@RequestParam("crowd_file") MultipartFile crowd_file,HttpSession session) {
	String idPicPath = null;
	Map<String, Integer> map = new HashMap<String, Integer>();
	//定义上传文件的路径
	// File.separator 就相当于/,这样写的目的是为了方便系统的迁移
       String filePath = session.getServletContext().getRealPath("static"+File.separator+"files"+File.separator+"product-images");
       //判断上传文件是否为空
	/*
	 * System.out.println(filePath); System.out.println(crowd_file);
	 */
       if(!crowd_file.isEmpty()) {
       	//获得原文件名
       	String oldName=crowd_file.getOriginalFilename();
       	//对文件名进行一个处理
       	String newFileName=System.currentTimeMillis()+RandomUtils.nextInt(100000,999999)+oldName;
       	//创建上传文件对象
       	File saveFile = new File(filePath,newFileName);
       	//判断文件上传对象是否存在,不存在就创建
       	if(!saveFile.exists()) {
       		saveFile.mkdirs();
       	}
       	//将文件进行上传
       	try {
       		crowd_file.transferTo(saveFile);
       		map.put("result", 1);	
		} catch (IllegalStateException e) {
			map.put("result", 0);
			e.printStackTrace();	
		} catch (IOException e) {
			map.put("result", 0);
			e.printStackTrace();
		}
       	// 将文件保存到本地文件夹中 F:/uploadFile/product文件夹中,这些文件夹需要自己提前建好
           try {
               DataInputStream dis = new DataInputStream(new FileInputStream(saveFile));
               DataOutputStream dos = new DataOutputStream(new FileOutputStream("F:/uploadFile"+"/product/"+newFileName));
               int len = -1;
               while ((len = dis.read()) != -1) {
                   dos.write(len);
               }
               dos.close();
               dis.close();
            //String  picPath = newFileName;
            //将上传文件保存调session中,方便做增加和修改的方法,
            session.setAttribute("productImage",newFileName);
           //System.out.println(newFileName);
           } catch (FileNotFoundException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
	return JSON.toJSONString(map);
}

做增加保存的时候就直接调用session中保存的图片的名称存到数据库中,然后清空session中的数据就行了,

//增加商品数据的请求	
@RequestMapping(value="/addProductList",method = RequestMethod.POST)
 @ResponseBody 
 public Object addProduct(Product product,HttpSession session) {
 Map<String, Integer> map = new HashMap<String, Integer>(); 
 //需要有创建者 
int createdBy=((User) session.getAttribute("loginuser")).getUid();
String productImage=(String) session.getAttribute("productImage");
product.setImg(productImage);
session.removeAttribute(productImage);
 //需要创建时间,获得系统的当前时间 
product.setCreateBy(createdBy); 
product.setCreateTime(new Date()); 
boolean isOk=productService.addProduct(product); 
if(isOk) { 
 map.put("result", 1);
 }else 
 { 
  map.put("result", 0);
 
 } 
return JSON.toJSONString(map);
}

做修改的时候就是要先判断session中保存的是否为空,不为空才进行修改,为空就取用页面传递过来的图片值。

//修改商品信息的请求
	@RequestMapping(value="/updateProduct",method=RequestMethod.POST)
	@ResponseBody
	public Object updateProduct(Product product,HttpSession session) {
	
	Map<String,Integer> map=new HashMap<String,Integer>();
	String productImage=(String) session.getAttribute("productImage");
	if(productImage!=null) {
		product.setImg(productImage);
		session.removeAttribute(productImage);
	}
	int uid=((User)session.getAttribute("loginuser")).getUid();
	product.setModifyBy(uid);
	product.setModifyTime(new Date());
	boolean isOk=productService.updateProduct(product);
	if(isOk)
	{
		map.put("result",1);
	}
	else {
		map.put("result",0);
	}
	return JSON.toJSONString(map);
	}	

那么上传增加成功之后如何在页面展示呢?
这里如果要使用本地服务器路径就直接使用controller中的服务器路径来展示图片
如果需要使用本地磁盘路径就需要在server.xml中进行一个配置:
server.xml中配置如下代码

<Context crossContext="true" debug="0" docBase="F:\uploadFile" path="/imgUrl" reloadable="true"/> 
<!-- 注意:一定是在<Host>标签内加这句话,否则是没有用的 -->

然后就是在页面中引入并展示,src="/imgUrl/你存放图片文件的文件夹/保存到数据库的图片名称"

<td class="text-center">
<img alt="商品图片" src="/imgUrl/product/${pro.img}" class="img-circle" style="height: 50px; width: 50px;">
</td>
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值