H5使用Ajax提交包含文件的Form表单,java获取form表单中的字段和文件

先上h5代码

  <form id="formId" class="am-form am-form-horizontal"  enctype="multipart/form-data">
          
        
              
            <div class="am-form-group">
              <label for="materialplace" class="am-u-sm-3 am-form-label">地址                
           </label>
              <div class="am-u-sm-9">
                <input type="text" id="address" name="address" placeholder="请输入地址">
              </div>
            </div>
              

              
            <div class="am-form-group">
              <label for="user-intro" class="am-u-sm-3 am-form-label">图片上传</label>
              <div class="am-u-sm-9">
                <input type="file" name="img" size="20" style="margin-top: 5px;" />
              </div>
            </div>

         
          </form>

             <div class="am-form-group">
              <div class="am-u-sm-9 am-u-sm-push-3" style="margin-top: 10px;margin-bottom: 20px;">
                <button type="button" onclick="submit()" class="am-btn am-btn-primary" >保存图片和地址</button>
              </div>
            </div>

j使用ajax提交表单

<script>

function submit() {
	console.log("into submit2")
	 var formData = new FormData($("#formId")[0]);
	    $.ajax({
	        async : false,
	        cache : false,
	        type : "post",
	        data : formData,
	        url : '你的后端地址!',
	        dataType : 'json',
	        contentType: false, //必须
	        processData: false, //必须
	        success : function(data) {
	           if(data.success){
	        	   alert("添加成功")
	           }else{
	        	   alert("添加失败")
	           }
	        },
	        error : function(){
	        	console.log('error');
	        }
	    	
	    });
	    }

	


</script>

java接收代码

 

@RequestMapping("/addtask")
	public void addtask(HttpServletRequest request, HttpServletResponse response)
			throws FileUploadException, IOException {
		System.err.println("into addtask------------");
		try {
			// 解析请求中的数据
			MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
			

			MultipartFile file = mpRequest.getFile("img");
			String path;
			String osName = System.getProperties().getProperty("os.name");
			if (osName.equals("Linux")) {
				path = "/usr/local/img/";
			} else {
				path = "D:\\upload";
			}

			// 上传文件的真实名称
			String name = file.getOriginalFilename();
			//保存在服务器中的文件名 
			String imageUrl = uploadFile(file, path);
				

			//具体ajax返回对象 可以自定义
			ExtResult ext = ExtResult.NEW();
			ext.setSuccess(true);
			ext.setMsg("添加成功");
			ResponseUtils.OutJSON(response, ext);

		} catch (Exception e) {
			e.printStackTrace();
			ExtResult ext = ExtResult.NEW();
			ext.setSuccess(false);
			ResponseUtils.OutJSON(response, ext);
		}

	}


    public String uploadFile(MultipartFile file, String path) throws IOException{
		//上传文件的真实名称
		String name = file.getOriginalFilename();
		//System.out.println(name);
		//获取后缀名
		String suffixName = name.substring(name.lastIndexOf("."));
		//System.out.println(suffixName);
		//自定义随机数
		String hash = Integer.toHexString(new Random().nextInt());
		String fileName = hash + suffixName;
		//System.out.println(fileName);
		
		File tempFile = new File(path, fileName);
		if(!tempFile.getParentFile().exists()){
			tempFile.getParentFile().mkdir();
		}
		if(tempFile.exists()){
			tempFile.delete();
		}
		tempFile.createNewFile();
		file.transferTo(tempFile);
		return tempFile.getName();
	}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值