菜单

ajaxFileupload实现多文件上传效能

2018年12月19日 - Ajax

开拓google 搜索”ajaxFileupload’
‘多文件上传”可以搜到许许多多好像之,这我何以还要写一下呢?
一个凡对准前大神的贡献表示感谢;二独凡是和谐知识的总计;四个是协调以旧的基础及改变了产,在那个记录,可能拉其他朋友。

图片 1

于是了之插件的还知情之插件的主导用法,我即便未赘述,直接上代码。

效果图.png

自己要贯彻五只公文上传,此前的做法是概念多独不同id的input,然后将ajaxfileuplod方法在for循环里,这么些办法是在网上看底,我道有些好,后边在网上找到的,就高级点了,间接改源码(因为作者长时间没跟新了,也确满意不了要求了)。接下来看看自家是怎么转的。

<div align="center" class="div_row">
  <form method="post" action="{:url('file/editAct')}">
    <table width="674" cellpadding="3" cellspacing="1">
      <tr>
        <td width="90" nowrap="nowrap"><div align="center">文件名</div></td>
        <td nowrap="nowrap"><div align="center">
          <input name="file_name" type="text" id="file_name" style="width:99%;" value="{$file.file_name}" {if empty($file.uid)} readonly {/if}/>
        </div></td>
        <td width="90" nowrap="nowrap"><div align="center">文件大小</div></td>
        <td nowrap="nowrap" width="100"><div align="center">
          <input name="file_size" type="text" id="file_size" style="width:90%;" value="{$file.file_size}"; readonly/>
          <input name="file_path" type="hidden" id="file_path" style="width:90%;" value="{$file.file_path}"; readonly/>
        </div></td>
      </tr>
      <tr>
        <td nowrap="nowrap"><div align="center">文件描述</div></td>
        <td nowrap="nowrap" colspan="3"><div align="center">
          <textarea name="description" rows="6" id="description" style="width:99%;">{$file.description}</textarea>
        </div></td>
      </tr>
      <tr>
          <td colspan="4" nowrap="nowrap"><div align="center">
            <input name="uid" type="hidden" id="uid" value="{$file.uid}" />
            <input type="submit" name="submit" id="button" value="确定编辑"/>
          </div></td>
      </tr>
    </table>
  </form>
</div>

var htmlModalFile = [
    '<div class="modal" id="modal-upload" >',
    '   <div class="modal-dialog" style="top:160px;text-align:center;">',
    '       <div class="modal-content" >',
    '           <div class="modal-header" >',
    '               <button type="button" class="close" data-dismiss="modal">×Close</button>',
    '               <h4 class="modal-title">选择文件上传</h4>',
    '           </div>',
    '           <div class="modal-body" style="text-align:left;margin-top:10px;">',
    '               <iframe name="myframe" src="" frameborder="0" style="display:none;"></iframe>',
    '               <form name="form-file" id="form-file" method="post" enctype="multipart/form-data" action="upload" target="myframe">',
    '                   <div style="text-align:left;">',
    '                       <label>存放路径:</label>',
    '                       <select name="save_type" id="save_type" style="width:100px;">',
    '                           <option value="file/attach">file/attach</option>',
    '                           <option value="file/paper">file/paper</option>',
    '                           <option value="file/default">file/default</option>',
    '                       </select>',
    '                   </div>',
    '                   <div style="text-align:left;margin-top:10px;"">',
    '                       <label>存放路径:</label>',
    '                       <input type="file" id="file" name="file" style="width:250px;height:25px;;background:white">',
    '                   </div>',
    '               </form>',
    '               <button data-dismiss="modal" id="btn_upload" style="position:absolute;right:10px;top:50%;height:100%;width:70px;height: 70px;margin-top: -35px">确定</button>',
    '           </div>',
    '       </div>',
    '   </div>',
    '</div>',
].join('');

$(function() {
    var modalFile = $(htmlModalFile);

    $('body').append(modalFile);

    $("#file_name").click(function () {
        $("#modal-upload").modal("toggle");
    });
    $("#btn_upload", modalFile).on("click", function () {
        var formData = new FormData($("#form-file")[0]);
        $.ajax({
            url: '/admin/file/upload',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                var par1 = window.document.getElementById('file_name');
                $(par1).attr('value', data['name']);
                var par2 = window.document.getElementById('file_size');
                $(par2).attr('value', data['size']);
                var save_type = $('#save_type option:selected') .val();
                $("#file_path").attr('value' ,save_type);
                alert(data['msg']);
            },
            error: function (data) {
                alert('ajax请求失败');
            }
        });
        return false;
    });
});

 /*
     * 保存文件基本信息
     */
    public function editAct(Request $request)
    {
        $data = $this->getParams(array('uid', 'file_name', 'description', 'file_size', 'file_path'));
        $data['edit_time'] = time();
        $data['app_name'] = get_app_name();
        if (!empty($data['uid'])) {
            $origin_data = Db::table('h_file')->where(['uid' => $data['uid']])->find();
            if ($origin_data['file_name'] != $data['file_name']) {
                $origin_name = get_down_path($origin_data['file_name'], $origin_data['file_path']);
                $new_name = get_down_path($data['file_name'], $data['file_path']);
                rename($origin_name, $new_name);
            }
        }
        if (!empty($data['uid'])) {
            Db::table('h_file')->where('uid', $data['uid'])->update($data);
            return $this->success('文件编辑成功!', url('file/edit', ['uid' => $data['uid']]));
        } else {
            $data['uid'] = create_uuid();
            Db::table('h_file')->insert($data);
            return $this->success('文件添加成功!', url('file/index'));
        }
    }

    public function upload(Request $request)
    {
        // 获取表单上传文件
        $file = $request->file('file');
        $save_type = $request->param('save_type');
        if (empty($file)) {
            return json(array('code' => -1, 'msg' => '请选择上传文件'));
        }
        $name = $file->getInfo('name');
        $file_path = get_down_path($save_type, '');
        if (file_exists(join_url($file_path, $name))) {
            return json(array('code' => -3, 'msg' => '文件已经存在','name' => $file->getInfo('name'),'size' => $file->getInfo('size')));
        }
        $info = $file->move($file_path, '');
        if ($info) {
            $file_info = $info->getInfo();
            return json(array('code' => 0, 'msg' => '文件上传成功', 'name' => $file_info['name'], 'size' => $file_info['size']));
        } else {
            // 上传失败获取错误信息`
            return json(array('code' => -2, 'msg' => '文件上传失败'));
        }
    }

引用网上的做法:

1、看无改动前的代码

var oldElement = jQuery('#' + fileElementId); 
var newElement = jQuery(oldElement).clone(); 
jQuery(oldElement).attr('id', fileId); 
jQuery(oldElement).before(newElement); 
jQuery(oldElement).appendTo(form); 

良容易看,这么些即便是将id为何的input加到from里去,那么一旦促成两个公文上传,就改变化下面的规范:

if(typeof(fileElementId) == 'string'){ 
 fileElementId = [fileElementId]; 
} 
for(var i in fileElementId){ 
 var oldElement = jQuery('#' + fileElementId[i]); 
 var newElement = jQuery(oldElement).clone(); 
 jQuery(oldElement).attr('id', fileId); 
 jQuery(oldElement).before(newElement); 
 jQuery(oldElement).appendTo(form); 
} 

 这样改后,初步化的代码就要这么形容:

$.ajaxFileUpload({ 
 url:'/ajax.php', 
 fileElementId:['id1','id2']//原先是fileElementId:'id' 只能上传一个 
}); 

到此地,确实好上传三个文本,不过对自己来说新题材同时来,六只id,我之界面的文书不是永恒的,是动态加载的,那么id要动态变化,我以为最累,为啥不获得name呢?然后将上述代码改呢如下:

if(typeof(fileElementId) == 'string'){ 
   fileElementId = [fileElementId]; 
  } 
  for(var i in fileElementId){ 
   //按name取值 
   var oldElement = jQuery("input[name="+fileElementId[i]+"]"); 
   oldElement.each(function() { 
    var newElement = jQuery($(this)).clone(); 
    jQuery(oldElement).attr('id', fileId); 
    jQuery(oldElement).before(newElement); 
    jQuery(oldElement).appendTo(form); 
   }); 
  } 

 这样改了 那么就好兑现多组多独文件上传,接下去看自己是怎么用的。

html:

<div> 
    <img id="loading" src="scripts/ajaxFileUploader/loading.gif" style="display:none;"> 

     <table cellpadding="0" cellspacing="0" class="tableForm" id="calculation_model"> 
      <thead> 
      <tr> 
       <th>多组多个文件</th> 
      </tr> 
      </thead> 
      <tbody> 
      <tr> 
       <td>第一组</td> 
       <td>第二组</td> 
      </tr> 
      <tr> 
       <td><input type="file" name="gridDoc" class="input"></td> 
       <td><input type="file" name="caseDoc" class="input"></td> 
      </tr> 
      </tbody> 
      <tfoot> 
      <tr> 
       <td><button class="button" id="up1">Upload</button></td> 
       <td><button class="button" id="addInput" >添加一组</button></td> 
      </tr> 
      </tfoot> 
     </table> 
   </div> 

js:

/** 
 * Created with IntelliJ IDEA. 
 * User: Administrator 
 * Date: 13-7-3 
 * Time: 上午9:20 
 * To change this template use File | Settings | File Templates. 
 */ 
$(document).ready(function () { 
 $("#up1").click(function(){ 
  var temp = ["gridDoc","caseDoc"]; 
  ajaxFileUpload(temp); 
 }); 

 $("#addInput").click(function(){ 
  addInputFile(); 
 }); 

}); 

//动态添加一组文件 
function addInputFile(){ 
 $("#calculation_model").append(" <tr>"+ 
  "<td><input type='file' name='gridDoc' class='input'></td> "+ 
  "<td><input type='file' name='caseDoc' class='input'></td> "+ 
  "</tr>"); 
} 


//直接使用下载下来的文件里的demo代码 
function ajaxFileUpload(id) 
{ 
 //starting setting some animation when the ajax starts and completes 
 $("#loading").ajaxStart(function(){ 
   $(this).show(); 
  }).ajaxComplete(function(){ 
   $(this).hide(); 
  }); 

 /* 
  prepareing ajax file upload 
  url: the url of script file handling the uploaded files 
  fileElementId: the file type of input element id and it will be the index of $_FILES Array() 
  dataType: it support json, xml 
  secureuri:use secure protocol 
  success: call back function when the ajax complete 
  error: callback function when the ajax failed 

  */ 
 $.ajaxFileUpload({ 
   url:'upload.action', 
   //secureuri:false, 
   fileElementId:id, 
   dataType: 'json' 
  } 
 ) 

 return false; 

} 

自我后台是故之struts2,strtus2的上传是相比较简单的,只要表明约定的名,即可取文件对象,和称号,代码如下:

package com.ssy.action; 

import com.opensymphony.xwork2.ActionSupport; 
import org.apache.commons.io.FileUtils; 
import org.apache.struts2.util.ServletContextAware; 

import javax.servlet.ServletContext; 
import java.io.*; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.Random; 

/** 
 * Created with IntelliJ IDEA. 
 * User: Administrator 
 * Date: 13-7-2 
 * Time: 下午4:08 
 * To change this template use File | Settings | File Templates. 
 */ 
public class Fileupload extends ActionSupport implements ServletContextAware { 
 private File[] gridDoc,caseDoc; 
 private String[] gridDocFileName,caseDocFileName; 

 private ServletContext context; 



 public String execute(){ 
  for (int i = 0;i<gridDocFileName.length;i++) { 
   System.out.println(gridDocFileName[i]); 
  } 
  for (int i = 0;i<caseDocFileName.length;i++) { 
   System.out.println(caseDocFileName[i]); 
  } 


  //System.out.println(doc1FileName); 
  //System.out.println(doc2FileName); 
  String targetDirectory = context.getRealPath("/uploadFile"); 

  /* 
   *这里我只取得 第一组的文件进行上传,第二组的类似 
  */ 
 try{ 
   for (int i = 0; i < gridDoc.length; i++) { 
    String targetFileName = generateFileName(gridDocFileName[i]); 
    File target = new File(targetDirectory, targetFileName); 
    FileUtils.copyFile(gridDoc[i], target); 
   } 
  }catch (Exception e){ 
   e.printStackTrace(); 
  }  

  return SUCCESS; 
 } 

 public File[] getGridDoc() { 
  return gridDoc; 
 } 

 public void setGridDoc(File[] gridDoc) { 
  this.gridDoc = gridDoc; 
 } 

 public File[] getCaseDoc() { 
  return caseDoc; 
 } 

 public void setCaseDoc(File[] caseDoc) { 
  this.caseDoc = caseDoc; 
 } 

 public String[] getGridDocFileName() { 
  return gridDocFileName; 
 } 

 public void setGridDocFileName(String[] gridDocFileName) { 
  this.gridDocFileName = gridDocFileName; 
 } 

 public String[] getCaseDocFileName() { 
  return caseDocFileName; 
 } 

 public void setCaseDocFileName(String[] caseDocFileName) { 
  this.caseDocFileName = caseDocFileName; 
 } 

 /** 
  * 用日期和随机数格式化文件名避免冲突 
  * @param fileName 
  * @return 
  */ 
 private String generateFileName(String fileName) { 
  System.out.println(fileName); 
  SimpleDateFormat sf = new SimpleDateFormat("yyMMddHHmmss"); 
  String formatDate = sf.format(new Date()); 
  int random = new Random().nextInt(10000); 
  int position = fileName.lastIndexOf("."); 
  String extension = fileName.substring(position); 
  return formatDate + random + extension; 
 } 

} 

描绘到此处,我虽发出疑点了,从前的深神改的大半文件,为啥要取id,而且后台是怎抱的,我要尚未怎么搞了解,我转之斯代码可行么?是无是是bug呢?这多少个还有待考验,如果见到问题,请提出,共同学习 

末附上,我修改后底插件

ajaxfileupload插件.rar)

以上就是本文的全体内容,希望对我们的攻有助,也期我们多多协助脚本的拙。

君可能感兴趣的篇章:

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图