文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java使用Ajax异步上传文件

2024-04-02 19:55

关注

相关代码示例:

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或者是其它对象存储):


   
@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}" 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异步上传文件的详细内容,更多关于Java 用Ajax上传文件的资料请关注编程网其它相关文章!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯