溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用Ajax進行文件與其他參數(shù)的上傳功能

發(fā)布時間:2021-07-09 14:35:32 來源:億速云 閱讀:147 作者:小新 欄目:web開發(fā)

這篇文章主要為大家展示了“如何使用Ajax進行文件與其他參數(shù)的上傳功能”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何使用Ajax進行文件與其他參數(shù)的上傳功能”這篇文章吧。

操作步驟:

1 導(dǎo)入jar包:

我們在使用文件上傳時,需要使用到兩個jar包,分別是commons-io與commons-fileupload,在這里我使用的兩個版本分別是2.4與1.3.1版本的,需要使用JS文件與jar包最后會發(fā)給大家一個連接(如何失效請直接我給留言,我會及時更改,謝謝)。

2 修改配置文件:

當(dāng)我們導(dǎo)入的jar包是不夠的,我們需要使用到這些jar包,由于我當(dāng)時使用的是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有很多的好處,比如當(dāng)我們不需要刷新頁面獲希望進行局部刷新的時候,我們就可以使用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>發(fā)布資訊</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,//是否需要安全協(xié)議
   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("系統(tǒng)錯誤");
       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">
        <h4>
         <span>發(fā)布資訊</span>
        </h4>
       </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>標(biāo)題</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" >請選擇標(biāo)題!</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>內(nèi)容</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>選擇行業(yè)</strong></p>
            <p class="colse_tip" id="type_p_info" >請選擇行業(yè)!</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">生物醫(yī)藥</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();">發(fā)布</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>

上面的代碼是我在項目實際開發(fā)的過程中所用的代碼,具體的CSS文件與JS文件我已經(jīng)刪掉了,但是不會影響具體的操作,大家使用的時候只需要把其中的class文件刪掉了就可以了。好了,我們在說一說上面的代碼。首先為大家解釋一下ctx的作用,在我們項目開發(fā)的過程中,我們要求必須使用絕對路徑,所有{ctx}是我們封裝好的一個東西,就是我們的服務(wù)器地址+端口號+項目名稱。當(dāng)我們使用的時候,只需要引用一下文件,就是上面直接使用的<%@ include file=”../commons/taglibs.jsp”%>,當(dāng)我們用的時候直接使用${ctx}就可以,大家在使用的時候就直接使用自己的本機地址端口號與項目名稱就可以。后面的/resources/new_js/jquery.js就是我們要使用的jqery.js文件的存放地址。
其實在上面的Ajax的操作中,我相當(dāng)于做了兩次的Ajax的提價,但是在第一次提交的時候,后臺給我們返回一個參數(shù),就是我們的文件存放路徑與文件名稱,在第二次提交的時候,我們將這些參數(shù)與其他參數(shù)同時上傳到后臺,并將這些參數(shù)保存到數(shù)據(jù)庫中,以便我們使用。

* 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("數(shù)據(jù)長度========>>>>>>>>>>" + 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工具類,并將文件上傳到服務(wù)器中,在上傳的過程中,我首先做了一個文件唯一名稱的操作,就是獲取當(dāng)前時間的毫秒數(shù),雖然不能絕對保證,但是到并發(fā)量小的時候可以保證不會造成文件名稱重復(fù)。然后,我將文件上傳的路徑的上傳地址寫到了.properties中,這樣的好處是當(dāng)我們想更換文件上傳的路徑時,我們就可以直接修改.properties文件,而讀取.properties文件的具體方式在我的另一篇文章中講到。最后,我們在開發(fā)的過程中,文件保存一般是保存到文件服務(wù)器中,而文件服務(wù)器一般是在Linux中,而在不同的服務(wù)器中,路徑是使用斜杠還是反斜杠是不同的,所有我在這里面使用了File.separator來代替,F(xiàn)ile.separator在不同的系統(tǒng)中可以自動生成斜杠獲反斜杠。

以上是“如何使用Ajax進行文件與其他參數(shù)的上傳功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI