您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
今天就跟大家聊聊有关如何在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。