使用Ajax上傳文件的應用場景頗多,好比上傳用戶頭像、博客文章中插入圖片、對認證用戶相關身份進行校驗等等不少不少。
下面貼相關代碼示例:
html代碼片斷: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代碼片斷:web
//上傳配置文件 $("#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或者是其它對象存儲):ajax
/** * 上傳文件 * @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; }