search
HomeBackend DevelopmentPHP TutorialAjax upload function of files and other parameters

记得前一段时间,为了研究Ajax文件上传,找了很多资料,在网上看到的大部分是form表单的方式提交文件,对于Ajax方式提交文件并且也要提交表单中其他数据,发现提及的并不是很多,后来在同事的帮助下,使用ajaxfileupload最终完成了文件上传与其他提交的操作,现在分享给大家,希望大家能有有所帮助。本文主要介绍了使用Ajax进行文件与其他参数的上传功能(java开发),非常不错,具有参考借鉴价值,需要的朋友参考下吧,希望能帮助到大家。

文件上传:

操作步骤:

1 导入jar包:

我们在使用文件上传时,需要使用到两个jar包,分别是commons-io与commons-fileupload,在这里我使用的两个版本分别是2.4与1.3.1版本的,需要使用JS文件与jar包最后会发给大家一个连接(如何失效请直接我给留言,我会及时更改,谢谢)。

2 修改配置文件:

当我们导入的jar包是不够的,我们需要使用到这些jar包,由于我当时使用的是SSM框架,所以我是在application-content.xml中配置一下CommonsMultipartResolver,具体配置方法如下:

<bean> 
  <property> 
   <value>104857600</value> 
  </property> 
  <property> 
   <value>4096</value> 
  </property> 
 </bean>

3 JSP文件:

大家对form表单提交问价的方式很熟悉,但是我们有很多情况下并不能直接使用form表单方式直接提交。这时候我们就需要使用Ajax方式提交,Ajax有很多的好处,比如当我们不需要刷新页面获希望进行局部刷新的时候,我们就可以使用Ajax。下面是我的表单提交的JSP页面,其中包含JS的详细步骤和HTML文件:



nbsp;html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


<meta>
<meta>
<meta>
<title>发布资讯</title>
 <script></script>
 <script></script>
 <script> 
 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 : &#39;file&#39;,
   type : &#39;POST&#39;, //文件提交的方式
   dataType : &#39;string&#39;,
   cache : false, //是否进行页面缓存
   async : true, // 是否同步提交
   success : function(data) { 
     $.ajax({
     url : &#39;${ctx}/info/addInfo?fileUrl=&#39;+data,
     type : &#39;post&#39;,
     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>


<p>
 <!--页面主体 start-->
 </p><p>
  </p><p>
   </p><p>
    </p><p>
     </p><p>
      </p><p></p>
     
     <p>
      </p><p>
       </p><p>
        </p><h3>
         <span>发布资讯</span>
        </h3>
       
       <p>
        </p>
                                                                                                                                                                                                                                                                                                                                                                                        

*标题

            
                         

                         

*摘要

            

*内容

            
            

*选择行业

            

请选择行业!

             

              请选择              

             

              

                   
  • 化工
  •                
  • 装备制造
  •                
  • 生物医药
  •                
  • 电子信息
  •                
  • 其他
  •               
                          
                                                      
        
               

        

         发布         

        

         取消         

                                    

上面的代码是我在项目实际开发的过程中所用的代码,具体的CSS文件与JS文件我已经删掉了,但是不会影响具体的操作,大家使用的时候只需要把其中的class文件删掉了就可以了。好了,我们在说一说上面的代码。首先为大家解释一下ctx的作用,在我们项目开发的过程中,我们要求必须使用绝对路径,所有{ctx}是我们封装好的一个东西,就是我们的服务器地址+端口号+项目名称。当我们使用的时候,只需要引用一下文件,就是上面直接使用的,当我们用的时候直接使用${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  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> 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);
 }</string></string></string></multipartfile></string>

在上面的代码中我们可以看到,在文件第一次上传的过程中,我们首先进入到doUpload中,然后使用uploadAttachment工具类,并将文件上传到服务器中,在上传的过程中,我首先做了一个文件唯一名称的操作,就是获取当前时间的毫秒数,虽然不能绝对保证,但是到并发量小的时候可以保证不会造成文件名称重复。然后,我将文件上传的路径的上传地址写到了.properties中,这样的好处是当我们想更换文件上传的路径时,我们就可以直接修改.properties文件,而读取.properties文件的具体方式在我的另一篇文章中讲到。最后,我们在开发的过程中,文件保存一般是保存到文件服务器中,而文件服务器一般是在Linux中,而在不同的服务器中,路径是使用斜杠还是反斜杠是不同的,所有我在这里面使用了File.separator来代替,File.separator在不同的系统中可以自动生成斜杠获反斜杠。

相关推荐:

ajax实现异步文件或图片上传功能实例分享

php网页常见文件上传功能的实现方法

javascript实现文件异步上传功能详解

The above is the detailed content of Ajax upload function of files and other parameters. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools