java获取ajax上传的文件,Java使用Ajax异步上传文件

相关代码示例:

html代码片段:

名称

class="layui-input">

描述

文件

请选择配置文件

立即提交

重置

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('上传失败!');

}

});

                                %24%7BformData.logoImg%7D

上传

#if>

#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异步上传文件的详细内容,更多关于Java 用Ajax上传文件的资料请关注脚本之家其它相关文章!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值