Java使用Ajax異步上傳文件
相關(guān)代碼示例:
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="請(qǐng)輸入配置名稱" 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="請(qǐng)輸入配置描述" 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">請(qǐng)選擇配置文件</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+騰訊云對(duì)象存儲(chǔ),可將其更換為其它對(duì)象存儲(chǔ),如七牛云、ftp或者是其它對(duì)象存儲(chǔ)):
/**
* 上傳文件
* @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);
//數(shù)據(jù)庫(kù)保存圖片地址
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, "參數(shù)異常");
}
} 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);
}
}
}
以上就是Java使用Ajax異步上傳文件的詳細(xì)內(nèi)容,更多關(guān)于Java 用Ajax上傳文件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Java使用Ajax實(shí)現(xiàn)跨域上傳圖片功能
- 解決java使用axios.js的post請(qǐng)求后臺(tái)時(shí)無(wú)法接收到入?yún)⒌膯?wèn)題
- vue+axios+java實(shí)現(xiàn)文件上傳功能
- java使用ajax完成上傳文件
- Java?axios與spring前后端分離傳參規(guī)范總結(jié)
- Java?Web中Ajax技術(shù)使用方法介紹
- java前后端使用ajax數(shù)據(jù)交互問(wèn)題(簡(jiǎn)單demo)
- JavaWeb中異步交互的關(guān)鍵Ajax詳解
- java中Ajax與Axios的使用小結(jié)
相關(guān)文章
Spring Boot實(shí)現(xiàn)接口簽名驗(yàn)證的過(guò)程
在Spring Boot中實(shí)現(xiàn)接口校驗(yàn)簽名通常是為了保證接口請(qǐng)求的安全性和數(shù)據(jù)的完整性,這篇文章主要介紹了Spring Boot實(shí)現(xiàn)接口簽名驗(yàn)證,需要的朋友可以參考下2024-04-04
子類繼承父類時(shí)構(gòu)造函數(shù)相關(guān)問(wèn)題解析
這篇文章主要介紹了子類繼承父類時(shí)構(gòu)造函數(shù)相關(guān)問(wèn)題解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
解析Spring Boot 如何讓你的 bean 在其他 bean&n
在 SpringBoot 中如何讓自己的某個(gè)指定的 Bean 在其他 Bean 前完成被 Spring 加載?我聽(tīng)到這個(gè)問(wèn)題的第一反應(yīng)是,為什么會(huì)有這樣奇怪的需求?下面小編給大家分析下Spring Boot 如何讓你的 bean 在其他 bean 之前完成加載 ,感興趣的朋友一起看看吧2024-01-01
spring security自定義認(rèn)證登錄的全過(guò)程記錄
這篇文章主要給大家介紹了關(guān)于spring security自定義認(rèn)證登錄的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12
maven中deploy命令報(bào)401錯(cuò)誤的原因及解決方案
在mac版idea使用過(guò)程中有時(shí)候會(huì)出現(xiàn)deploy時(shí)候報(bào)401錯(cuò)誤,所以本文給大家介紹了maven 中deploy命令報(bào)401錯(cuò)誤的原因及解決方案,文章通過(guò)圖文結(jié)合的方式講解的非常詳細(xì),需要的朋友可以參考下2024-05-05
Java如何將json字符串與實(shí)體類互相轉(zhuǎn)換
在我們調(diào)用三方平臺(tái)接口時(shí),經(jīng)常需要將我們封裝的實(shí)體類轉(zhuǎn)換為json作為傳參,下面這篇文章主要給大家介紹了關(guān)于Java如何將json字符串與實(shí)體類互相轉(zhuǎn)換的相關(guān)資料,需要的朋友可以參考下2023-11-11

