springmvc实现异步上传文件

Java 发表评论

<div>
                               <div class="file" style="float: left;">             
                                     <input type="file" name="file"id="file" runat="server" >
                                     <input type="hidden" name='expoid'id="expoid" value="${expoid}" class="form-control">
                               </div>
                               <div>
                                     <button type="button" class="btn btn-info" id="btnUpload"  onclick="uploadImage()" value="上传">上传</button>
                               </div>          
                         </div>

 function uploadImage() {
			 var input = $("#file");
		        //判断是否有选择上传文件
		            var file = $("#file").val();
		            if (file == "") {
		                alert("请选择上传。doc文档文件!");
		                return;
		            }
		            //判断上传文件的后缀名
		            var strExtension = file.substr(file.lastIndexOf('.') + 1);
		            if (strExtension != 'doc') {
		                alert("请选择word文档文件");
		                return;
		            }
		            //上传文件
	                var formData = new FormData();
	                formData.append('expoid',$("#expoid").val());
	                formData.append('file',input[0].files[0]);
	                layer.load(1, {
	                      shade: [0.1,'#fff'] //0.1透明度的白色背景
	                });
	                $.ajax({
	                    type: "POST", // 上传文件要用POST
	                    url: "${ctx}/expo/exhibitionpo/uploadfile",
	                    dataType : "json",
	                    crossDomain: true, // 如果用到跨域,需要后台开启CORS
	                    processData: false,  // 注意:不要 process data
	                    contentType: false,  // 注意:不设置 contentType
	                    data: formData
	                }).success(function(data) {
	                    $("#fileName").innerHTML=data.fileName;
	                    $("#timeDate").innerHTML =data.timeDate;
	                    $("#userName").innerHTML =data.userName;
	                    layer.alert("文件上传成功!",{icon:1});
	                    layer.closeAll('loading');
	                }).fail(function(data) {
	                    layer.alert("网络错误,请刷新后重试!",{icon:2});
	                });
		        }

	// 附件上传
	@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadTest(@RequestParam(required = false, value = "file") MultipartFile file,
			@RequestParam(required = false, value = "expoid") String expoid, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, String> reMap = new HashMap<String, String>();
		User user = UserUtils.getUser();
		String path = request.getSession().getServletContext().getRealPath("fujianTemplate");
		String fileName = file.getOriginalFilename();
		System.out.println(fileName);
		System.out.println(path);
		String newFileName = expoid + "_fujian.doc";
		System.out.println(newFileName);
		File targetFile = new File(path, newFileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		try {
			file.transferTo(targetFile);
			Date d = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateNowStr = sdf.format(d);
			reMap.put("fileName", newFileName);
			reMap.put("timeDate", dateNowStr);
			reMap.put("userName", user.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}

		return reMap;
	}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

昵称 *