文件上传:
记得前一段时间,为了研究Ajax文件上传,找了很多资料,在网上看到的大部分是form表单的方式提交文件,对于Ajax方式提交文件并且也要提交表单中其他数据,发现提及的并不是很多,后来在同事的帮助下,使用ajaxfileupload最终完成了文件上传与其他提交的操作,现在分享给大家,希望大家能有有所帮助。
操作步骤:
1 导入jar包:
我们在使用文件上传时,需要使用到两个jar包,分别是commons-io与commons-fileupload,在这里我使用的两个版本分别是2.4与1.3.1版本的,需要使用JS文件与jar包最后会发给大家一个连接(如何失效请直接我给留言,我会及时更改,谢谢)。
2 修改配置文件:
当我们导入的jar包是不够的,我们需要使用到这些jar包,由于我当时使用的是SSM框架,所以我是在application-content.xml中配置一下CommonsMultipartResolver,具体配置方法如下:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean>
3 JSP文件:
大家对form表单提交问价的方式很熟悉,但是我们有很多情况下并不能直接使用form表单方式直接提交。这时候我们就需要使用Ajax方式提交,Ajax有很多的好处,比如当我们不需要刷新页面获希望进行局部刷新的时候,我们就可以使用Ajax。下面是我的表单提交的JSP页面,其中包含JS的详细步骤和HTML文件:
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ include file="../commons/taglibs.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>发布资讯</title> <script type="text/javascript" src="${ctx}/resources/new_js/jquery.js"></script> <script type="text/javascript" src="${ctx}/resources/js/ajaxfileupload.js"></script> <script type="text/javascript"> function save(){ var typeId = $("#type_span_info").attr("data-id"); if (typeof (typeId) == "undefined") { $("#type_p_info").show(); return; } else { $("#type_p_info").hide(); } var title = $("#title_input_info").val(); var summary = $("#summary_input_info").val(); var content = $("#content_textarea_info").val(); $.ajaxFileUpload({ url : "${ctx}/info/doUpload", secureuri : false,//是否需要安全协议 fileElementId : 'file', type : 'POST', //文件提交的方式 dataType : 'string', cache : false, //是否进行页面缓存 async : true, // 是否同步提交 success : function(data) { $.ajax({ url : '${ctx}/info/addInfo?fileUrl='+data, type : 'post', data:{title:title,summary:summary,content:content,typeId:typeId}, async : false, success : function(result) { if (result == 1) { $("#del_prompt_p").text("添加成功"); fnError3(); } else if (result == 2) { $("#del_prompt_p").text("添加失败") fnError2(); } else { $("#del_prompt_p").text("系统错误"); fnError2(); } } }); } }); } </script> </head> <body class="body_bg"> <div class="main"> <!--页面主体 start--> <div class="main_content"> <div class="later_index clear wrap"> <div class="later_right fr"> <div class="roll_parent" id="roll_parent"> <div class="scroll_parent" id="scroll_parent"> <div class="scroll" id="scroll"></div> </div> <div class="roll_son" id="roll_son"> <div class="later_content later_content1"> <div class="release_name"> <h3> <span>发布资讯</span> </h3> </div> <div class="issue_content"> <form action="" id="form1" method="post" enctype="multipart/form-data"> <table class="issue_tab"> <tbody> <tr> <td><p><i>*</i><strong>标题</strong></p> </td> </tr> <tr> <td><input id="title_input_info" name="title_input_info" type="text" placeholder="最多可以输入40个字" type="text" maxlength="40"/> <!-- <span class="colse"></span> --> <p class="colse_tip"></p> <!-- <p class="colse_tip" id="title_p_info" style="display:hidden;">请选择标题!</p> --> </td> </tr> <tr> <td><p><i>*</i><strong>摘要</strong></p></td> </tr> <tr> <td><input name="summary_input_info" id="summary_input_info" type="text" placeholder="最多可以输入100个字" type="text" maxlength="100" /> <p class="colse_tip"></p></td> </tr> <tr> <td><p><i>*</i><strong>内容</strong></p> </td> </tr> <tr> <td><textarea name="content_textarea_info" id="content_textarea_info"></textarea> <p class="colse_tip"></p></td> </tr> <tr> <td><p><i>*</i><strong>选择行业</strong></p> <p class="colse_tip" id="type_p_info" style="display:hidden;">请选择行业!</p></td> </tr> <tr> <td> <div class="next_select select_width select_bg" id="next_select0"> <span id="type_span_info">请选择</span> </div> <div class="select_box select_top select_width" data-id="" id="select_box0"> <ul> <li class="curr" data-id="2">化工</li> <li data-id="3">装备制造</li> <li data-id="4">生物医药</li> <li data-id="5">电子信息</li> <li data-id="6">其他</li> </ul> </div> </td> </tr> <tr> <td> <input type="button" class="isue_inp_btn" value="添加图片"/> <input type="text" id="issue_input_text" class="issue_text" /> <input type="file" id="file" name="file" class="issue_file" onchange="javaScript:validate_img(this)" /> </td> </tr> </tbody> </table> </form> </div> <div class="financial_pro_icon"> <div class="financial_pro_icon_l issue_btn1"> <a href="javaScript:save();">发布</a> </div> <div class="financial_pro_icon_r issue_btn1"> <a href="${ctx}/info/gotoInfo?index=2">取消</a> </div> </div> </div> </div> </div> </div> </div> </div> <!--页面主体 end--> </div> </body> </html>
上面的代码是我在项目实际开发的过程中所用的代码,具体的CSS文件与JS文件我已经删掉了,但是不会影响具体的操作,大家使用的时候只需要把其中的class文件删掉了就可以了。好了,我们在说一说上面的代码。首先为大家解释一下ctx的作用,在我们项目开发的过程中,我们要求必须使用绝对路径,所有{ctx}是我们封装好的一个东西,就是我们的服务器地址+端口号+项目名称。当我们使用的时候,只需要引用一下文件,就是上面直接使用的101b68d967a95f6ad2ccc9d50099fe4d,当我们用的时候直接使用${ctx}就可以,大家在使用的时候就直接使用自己的本机地址端口号与项目名称就可以。后面的/resources/new_js/jquery.js就是我们要使用的jqery.js文件的存放地址。
其实在上面的Ajax的操作中,我相当于做了两次的Ajax的提价,但是在第一次提交的时候,后台给我们返回一个参数,就是我们的文件存放路径与文件名称,在第二次提交的时候,我们将这些参数与其他参数同时上传到后台,并将这些参数保存到数据库中,以便我们使用。
* 4 后台代码:
//文件上传 @RequestMapping(value = "/doUpload", method = RequestMethod.POST, produces = "text/html; charset=UTF-8") @ResponseBody public String doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { List<String> fileNames = null; if (request instanceof MultipartHttpServletRequest) { // process the uploaded file logger.info("=====进入文件类型选择====="); fileNames = uploadAttachment(request, "file"); } String url = ""; if (fileNames.size() > 0) { for (int i = 0; i < fileNames.size(); i++) { url = url + fileNames.get(i); if(i < fileNames.size() - 1){ url = url + ","; } } } return url; } //文件上传的工具类 public List<String> uploadAttachment(HttpServletRequest request, String type) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; List<MultipartFile> files = multipartRequest.getFiles(type); logger.info("数据长度========>>>>>>>>>>" + files.size()); Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); int month = now.get(Calendar.MONTH) + 1; String realPath = PropertiesUtil.getProperty("realPath"); System.err.println("realpath=====>>>>>" + realPath); //String savePath = request.getSession().getServletContext().getRealPath("/") + "p_image\\" + type + "\\" + year+ "\\" + month + "\\"; String savePath = "government"+ File.separator + "image"+ File.separator + year+ File.separator + month + File.separator; logger.info("保存路径=====>" + savePath); List<String> fileNames = new ArrayList<String>(); for (MultipartFile multipartFile : files) { logger.info("--" + multipartFile.getOriginalFilename()); String fileName = multipartFile.getOriginalFilename(); String prefix = fileName.substring(fileName.lastIndexOf(".") + 1); String custName = "" + System.currentTimeMillis() + "." + prefix; if (UsedUtil.isNotNull(fileName)) { File targetFile = new File(realPath+savePath, custName); // fileName = year+"-"+month+"-"+fileName; if (!targetFile.exists()) { targetFile.mkdirs(); multipartFile.transferTo(targetFile); } try { } catch (Exception e) { e.printStackTrace(); } fileNames.add(savePath + custName); } } return fileNames; } //添加咨询 @RequestMapping(value = "/addInfo", method = RequestMethod.POST) @ResponseBody public Integer addInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileUrl) { InfoBean bean = new InfoBean(); if(UsedUtil.isNotNull(fileUrl)){ bean.setImagePath(fileUrl); } Map<String, Object> paramMap = ControllerUtil.request2Map(request); bean.setTitle((String) paramMap.get("title")); bean.setSummary((String) paramMap.get("summary")); bean.setContent((String) paramMap.get("content")); bean.setTypeId((String)paramMap.get("typeId")); return infoService.insInfo(bean); }
在上面的代码中我们可以看到,在文件第一次上传的过程中,我们首先进入到doUpload中,然后使用uploadAttachment工具类,并将文件上传到服务器中,在上传的过程中,我首先做了一个文件唯一名称的操作,就是获取当前时间的毫秒数,虽然不能绝对保证,但是到并发量小的时候可以保证不会造成文件名称重复。然后,我将文件上传的路径的上传地址写到了.properties中,这样的好处是当我们想更换文件上传的路径时,我们就可以直接修改.properties文件,而读取.properties文件的具体方式在Java开发中读取XML与properties配置文件的方法中讲到。最后,我们在开发的过程中,文件保存一般是保存到文件服务器中,而文件服务器一般是在Linux中,而在不同的服务器中,路径是使用斜杠还是反斜杠是不同的,所有我在这里面使用了File.separator来代替,File.separator在不同的系统中可以自动生成斜杠获反斜杠。
以上所述是小编给大家介绍的使用Ajax进行文件与其他参数的上传功能(java开发),希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的,在此也非常感谢大家PHP中文网的支持!
更多使用Ajax进行文件与其他参数的上传功能(java开发)相关文章请关注PHP中文网!

JVM通过字节码解释、平台无关的API和动态类加载实现Java的WORA特性:1.字节码被解释为机器码,确保跨平台运行;2.标准API抽象操作系统差异;3.类在运行时动态加载,保证一致性。

Java的最新版本通过JVM优化、标准库改进和第三方库支持有效解决平台特定问题。1)JVM优化,如Java11的ZGC提升了垃圾回收性能。2)标准库改进,如Java9的模块系统减少平台相关问题。3)第三方库提供平台优化版本,如OpenCV。

JVM的字节码验证过程包括四个关键步骤:1)检查类文件格式是否符合规范,2)验证字节码指令的有效性和正确性,3)进行数据流分析确保类型安全,4)平衡验证的彻底性与性能。通过这些步骤,JVM确保只有安全、正确的字节码被执行,从而保护程序的完整性和安全性。

Java'splatFormIndepentEncealLowsApplicationStorunonAnyOperatingsystemwithajvm.1)singleCodeBase:writeandeandcompileonceforallplatforms.2)easileupdates:updatebybytecodeforsimultaneDeployment.3)testOnOneOnePlatForforuluniverSalpeforuluniverSaliver.4444.4444

Java的平台独立性通过JVM、JIT编译、标准化、泛型、lambda表达式和ProjectPanama等技术不断增强。自1990年代以来,Java从基本的JVM演进到高性能的现代JVM,确保了代码在不同平台的一致性和高效性。

Java如何缓解平台特定的问题?Java通过JVM和标准库来实现平台无关性。1)使用字节码和JVM抽象操作系统差异;2)标准库提供跨平台API,如Paths类处理文件路径,Charset类处理字符编码;3)实际项目中使用配置文件和多平台测试来优化和调试。

java'splatformentenceenhancesenhancesmicroservicesharchitecture byferingDeploymentFlexible,一致性,可伸缩性和便携性。1)DeploymentFlexibilityAllowsibilityAllowsOllowsOllowSorlowsOllowsOllowsOllowSeStorunonAnyPlatformwithajvM.2)penterencyCrossServAccAcrossServAcrossServiCessImplifififiesDeevelopmentandeDe

GraalVM通过三种方式增强了Java的平台独立性:1.跨语言互操作,允许Java与其他语言无缝互操作;2.独立的运行时环境,通过GraalVMNativeImage将Java程序编译成本地可执行文件;3.性能优化,Graal编译器生成高效的机器码,提升Java程序的性能和一致性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

记事本++7.3.1
好用且免费的代码编辑器

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Dreamweaver CS6
视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。