Java 는 Ajax 비동기 로 파일 을 업로드 합 니 다.

관련 코드 예시:
html 코드 세 션:

                   <form class="layui-form" action="#" id="uploadForm">
	<div class="layui-form-item">
		<label class="layui-form-label">  </label>
		<div class="layui-input-block">
			<input type="text" id="config_name" placeholder="       " autocomplete="off"
				class="layui-input">
		</div>
	</div>


	<div class="layui-form-item layui-form-text">
		<label class="layui-form-label">  </label>
		<div class="layui-input-block">
			<textarea id="config_desc" placeholder="       " class="layui-textarea"></textarea>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">  </label>
		<div class="layui-input-block">
			<input type="file" name="file">
			<p class="help-block">       </p>
		</div>
	</div>




	<div class="layui-form-item">
		<div class="layui-input-block">
			<button class="layui-btn" id="save_config_file">    </button>
			<button type="reset" class="layui-btn layui-btn-primary">  </button>
		</div>
	</div>

</form>
js 코드 세 션:

//      
$("#save_config_file").click(function () {

	var name = $("#config_name").val();
	var desc = $("#config_desc").val();
	var userId = $("#userId").val();

	var formData = new FormData($("#uploadForm")[0]);

	formData.append("name",name);
	formData.append("desc",desc);
	formData.append("userId",userId);

		$.ajax({
			url: 'http://localhost:8090/bfi-web/api/ide/settings/uploadFiles',
			type: 'POST',
			data: formData,
			async: false,
			cache: false,
			contentType: false,
			processData: false,
			success: function (returndata) {

				layui.use('layer', function () {
					var layer = layui.layer;

					layer.msg(returndata.returnMsg, {
						icon: 1
					});
				});

				setTimeout(() => {

					closeLayui();

				}, 300);

			},
			error: function (returndata) {
				console.log("====================Error==========================");
			}
		});





});
자바 코드 세 션(여 기 는 SpringMVC+텐 센트 클 라 우 드 대상 저장 소 입 니 다.이 를 다른 대상 으로 저장 할 수 있 습 니 다.예 를 들 어 7 우 클 라 우 드,ftp 또는 다른 대상 저장 소):

   /**
    *     
    * @param request
    * @param file
    * @return
    */
@PostMapping(value="/uploadFiles",produces="application/json;charset=utf-8")
public JSONObject upModify(HttpServletRequest request, MultipartFile file) {
	
	JSONObject json = new JSONObject();

	try {
		
		COSClientUtil cosClientUtil = new COSClientUtil(); 

		if(!file.isEmpty()) {
			
			String name = cosClientUtil.uploadFile2Cos(file); 
               String desc = request.getParameter("desc");
               String names = request.getParameter("name");
               String userId = request.getParameter("userId");
               
               logger.info("desc:"+desc);
               logger.info("names:"+names);
               logger.info("userId:"+userId);
               
			//    
			logger.info("name = " + name);
			
			//      
			String imgUrl = cosClientUtil.getImgUrl(name); 

			logger.info("imgUrl = " + imgUrl);
			
			//         
			String dbImgUrl = imgUrl.substring(0,imgUrl.indexOf("?"));
			logger.info("dbImgUrl = " + dbImgUrl);
		
			IdeSettings ide = new IdeSettings();
			ide.setName(names);
			ide.setContent(dbImgUrl);
			ide.setUserId(userId);
			ide.setUpdateTime(DateUtil.date().toString());
			ide.setUploadTime(DateUtil.date().toString());
			ide.setDescription(desc);
			
			boolean isAddConfig = ideSettingsService.insert(ide);
			
			logger.info(isAddConfig);
			
			if(isAddConfig) {
				json.put(CommonEnum.RETURN_CODE, "000000");
				json.put(CommonEnum.RETURN_MSG, "    ");
			}else {
				json.put(CommonEnum.RETURN_CODE, "222222");
				json.put(CommonEnum.RETURN_MSG, "    ");
			}
			
	
			
		}else {
			json.put(CommonEnum.RETURN_CODE, "111111");
			json.put(CommonEnum.RETURN_MSG, "    ");
		}
		
	} catch (Exception e) {
		e.printStackTrace();

		json.put(CommonEnum.RETURN_CODE, "333333");
		json.put(CommonEnum.RETURN_MSG, "    ");

	}
       
       return json;
}
다른 예제:
1.jsp

$("#cxsc").click(function(){
                var bankId = $("#bankId").val();
                var formdata = new FormData();
                formdata.append('logo', $('#btnFile').get(0).files[0]);
                formdata.append('bankId', bankId);
                $.ajax({
                    type: 'POST',
                    url: './uploadLogo',
                    contentType : false,
                    data : formdata,
                    processData : false,
                    dataType: "json",
                    success: function (data) {
                        $("#logoImg").attr('src','${_b}/upload/banklogo/'+data.msg);
                    },
                    error : function(data) {
                        alert('    !');
                    }
                });
 
<#if formData?exists>
                            <#if (formData.logoImg??)>
                                <img src="${_b}/upload/banklogo/${formData.logoImg}" style="width:120px;height:120px;margin-bottom:5px;" id="logoImg"/>
                                <br/>
                                <input type="file" name="logo" id="btnFile" style="border:none;display:inline">
                                <button type="button" id="cxsc" style="display:inline">  </button>
                            <#else>
                                <input type="file" name="logo" style="border:none">
                            </#if>
                        <#else>
                            <input type="file" name="logo" style="border:none">
                        </#if>
2.controller

@RequestMapping(value = "/uploadLogo", method = {RequestMethod.POST})
    public void uploadLogo(
        @RequestParam(value = "bankId", required = true) String bankId,
        @RequestParam("logo") MultipartFile logo,
        HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        Json json = new Json();
        BankManage bankManage = bankManageService.getById(bankId);
        if (bankManage != null) {
            try {
                if (!logo.isEmpty()) {
                    String relativePath = "/upload/banklogo";
                    //      
                    String absolutePath = request.getSession().getServletContext().getRealPath(relativePath)+"\\"+bankManage.getLogoImg();
                    File oldfile = new File(absolutePath);
                    if (oldfile.exists()) {
                        oldfile.delete(); //      
                    }
                    String newPath = request.getSession().getServletContext().getRealPath(relativePath)+"\\"+logo.getOriginalFilename();
                    File newFile = new File(newPath);
                    logo.transferTo(newFile);
                    bankManage.setLogoImg(logo.getOriginalFilename());
                    bankManageService.update(bankManage);
                    json.setMsg(logo.getOriginalFilename());
                    writeJson(request, response, json);
                }else {
                    json.setMsg("    !");
                    writeJson(request, response, json);
                }
            }catch (Exception e) {
                e.printStackTrace();
                logger.error(e);
            }
        }
    }
이상 은 자바 가 Ajax 비동기 로 파일 을 업로드 하 는 상세 한 내용 입 니 다.자바 가 Ajax 로 파일 을 업로드 하 는 것 에 관 한 자 료 는 다른 관련 글 을 주목 하 세 요!

좋은 웹페이지 즐겨찾기