您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關如何在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=========================="); } }); });
Java代碼片段(這里是SpringMVC+騰訊云對象存儲,可將其更換為其它對象存儲,如七牛云、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}" id="logoImg"/> <br/> <input type="file" name="logo" id="btnFile" > <button type="button" id="cxsc" >上傳</button> <#else> <input type="file" name="logo" > </#if> <#else> <input type="file" name="logo" > </#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); } } }
看完上述內容,你們對如何在Java中使用Ajax異步上傳文件有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。