使用FormData上传文件

1.使用form表单


accept属性的介绍点这里

<form id="fileForm">
	<p>普通文本框:<input type="text" name="textInput"></p>
	<!-- multiple表示可以选择多个文件 -->
	<input type="file" name="file" id="file" multiple="multiple" accept="image/*">
	<input type="button" value="提交 " id="submitFileForm">
</form>

$("#submitFileForm").click(function(){
	var formData = new FormData($("#fileForm")[0]);
	$.ajax({
		url: '/uploadFile',
		type: 'post',
		data: formData,
		cache: false,
		contentType: false,
		processData: false,
		dataType: 'json',
		success: function(result){
			alert(result.message);
		}
	})
});

	@ResponseBody
	@RequestMapping("uploadFile")
	public String uplaodFile(HttpServletRequest request, HttpServletResponse response, 
			MultipartHttpServletRequest req) {
		Map<String, Object> map = new HashMap<String, Object>();
                //用到了jackson的jar包
		ObjectMapper mapper = new ObjectMapper();
		InputStream is = null;
		OutputStream os = null;
		try {
			//普通文本
			String str = request.getParameter("textInput");
			//文件
			List<MultipartFile> files = req.getFiles("file");
			for(MultipartFile file : files) {
				//对文件的大小、格式进行验证
				long fileSize = file.getSize();
				if(fileSize == 0) {
					throw new RuntimeException("请选择文件!");
				}
				String fileName = file.getOriginalFilename();
				String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
				if(fileSize > 5242880) {	//最大只能上传5M的(单位是字节)
					throw new RuntimeException("文件大小不能超过5M!");
				} else if(!".jpg".equals(fileSuffix) && !".png".equals(fileSuffix)) {	//只能上传png、jpg的的图片
					throw new RuntimeException("仅支持 png、jpg格式的文件!");
				}else {
					//文件符合要求进行上传操作
					String newFileName = System.currentTimeMillis() + fileSuffix;	//文件的新名字
					String uploadPath = request.getSession().getServletContext().getRealPath("");
					uploadPath += "/upload";
					File f = new File(uploadPath);
					if(!f.exists()) {
						f.mkdirs();
					}
					is = file.getInputStream();
					os = new FileOutputStream(uploadPath + "/" + fileName);
					byte[] b = new byte[1024];
					int len= 0;
					while((len = is.read(b)) != -1) {
						os.write(b, 0, len);
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			map.put("message", e.getMessage());
			try {
				return mapper.writeValueAsString(map);
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if(is != null) {
					is.close();
				}	
				if(os != null) {
					os.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		map.put("message", "上传成功!");
		try {
			return mapper.writeValueAsString(map);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}


2.不使用form表单

后台可以和上面使用一样的,就js部分有一点不一样

<input type="file" name="file" id="file" multiple="multiple" accept="image/*">
<input type="button" value="提交 " id="submitFileForm">

$("#submitFileForm").click(function(){
	var formData = new FormData();
	var file = $("#file")[0].files;
	for(var i = 0; i < file.length; i++){
		formData.append("file", file[i]);
	}
	$.ajax({
		url: '/uploadFile',
		type: 'post',
		data: formData,
		cache: false,
		contentType: false,
		processData: false,
		dataType: 'json',
		success: function(result){
			alert(result.message);
		} 
	})
});


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值