За последние 24 часа нас посетили 58958 программистов и 1772 робота. Сейчас ищет 921 программист ...

js

Тема в разделе "JavaScript и AJAX", создана пользователем rustoke, 29 дек 2014.

  1. rustoke

    rustoke Новичок

    С нами с:
    20 сен 2014
    Сообщения:
    145
    Симпатии:
    0
    На какой строчке здесь можно поменять имя загружаемого файла?

    Код (Text):
    1.  
    2. (function(){
    3.    
    4. var d = document, w = window;
    5.  
    6. /**
    7.  * Get element by id
    8.  */
    9. function get(element){
    10.     if (typeof element == "string")
    11.         element = d.getElementById(element);
    12.     return element;
    13. }
    14.  
    15. /**
    16.  * Attaches event to a dom element
    17.  */
    18. function addEvent(el, type, fn){
    19.     if (w.addEventListener){
    20.         el.addEventListener(type, fn, false);
    21.     } else if (w.attachEvent){
    22.         var f = function(){
    23.           fn.call(el, w.event);
    24.         };         
    25.         el.attachEvent('on' + type, f)
    26.     }
    27. }
    28.  
    29.  
    30. /**
    31.  * Creates and returns element from html chunk
    32.  */
    33. var toElement = function(){
    34.     var div = d.createElement('div');
    35.     return function(html){
    36.         div.innerHTML = html;
    37.         var el = div.childNodes[0];
    38.         div.removeChild(el);
    39.         return el;
    40.     }
    41. }();
    42.  
    43. function hasClass(ele,cls){
    44.     return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
    45. }
    46. function addClass(ele,cls) {
    47.     if (!hasClass(ele,cls)) ele.className += " "+cls;
    48. }
    49. function removeClass(ele,cls) {
    50.     var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
    51.     ele.className=ele.className.replace(reg,' ');
    52. }
    53.  
    54. // getOffset function copied from jQuery lib (http://jquery.com/)
    55. if (document.documentElement["getBoundingClientRect"]){
    56.     // Get Offset using getBoundingClientRect
    57.     // http://ejohn.org/blog/getboundingclientrect-is-awesome/
    58.     var getOffset = function(el){
    59.         var box = el.getBoundingClientRect(),
    60.         doc = el.ownerDocument,
    61.         body = doc.body,
    62.         docElem = doc.documentElement,
    63.        
    64.         // for ie
    65.         clientTop = docElem.clientTop || body.clientTop || 0,
    66.         clientLeft = docElem.clientLeft || body.clientLeft || 0,
    67.        
    68.         // In Internet Explorer 7 getBoundingClientRect property is treated as physical,
    69.         // while others are logical. Make all logical, like in IE8.
    70.        
    71.        
    72.         zoom = 1;
    73.         if (body.getBoundingClientRect) {
    74.             var bound = body.getBoundingClientRect();
    75.             zoom = (bound.right - bound.left)/body.clientWidth;
    76.         }
    77.         if (zoom > 1){
    78.             clientTop = 0;
    79.             clientLeft = 0;
    80.         }
    81.         var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop,
    82.         left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft;
    83.                
    84.         return {
    85.             top: top,
    86.             left: left
    87.         };
    88.     }
    89.    
    90. } else {
    91.     // Get offset adding all offsets
    92.     var getOffset = function(el){
    93.         if (w.jQuery){
    94.             return jQuery(el).offset();
    95.         }      
    96.            
    97.         var top = 0, left = 0;
    98.         do {
    99.             top += el.offsetTop || 0;
    100.             left += el.offsetLeft || 0;
    101.         }
    102.         while (el = el.offsetParent);
    103.        
    104.         return {
    105.             left: left,
    106.             top: top
    107.         };
    108.     }
    109. }
    110.  
    111. function getBox(el){
    112.     var left, right, top, bottom;  
    113.     var offset = getOffset(el);
    114.     left = offset.left;
    115.     top = offset.top;
    116.                        
    117.     right = left + el.offsetWidth;
    118.     bottom = top + el.offsetHeight;    
    119.        
    120.     return {
    121.         left: left,
    122.         right: right,
    123.         top: top,
    124.         bottom: bottom
    125.     };
    126. }
    127.  
    128. /**
    129.  * Crossbrowser mouse coordinates
    130.  */
    131. function getMouseCoords(e){    
    132.     // pageX/Y is not supported in IE
    133.     // http://www.quirksmode.org/dom/w3c_cssom.html        
    134.     if (!e.pageX && e.clientX){
    135.         // In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
    136.         // while others are logical (offset).
    137.         var zoom = 1;  
    138.         var body = document.body;
    139.        
    140.         if (body.getBoundingClientRect) {
    141.             var bound = body.getBoundingClientRect();
    142.             zoom = (bound.right - bound.left)/body.clientWidth;
    143.         }
    144.  
    145.         return {
    146.             x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
    147.             y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
    148.         };
    149.     }
    150.    
    151.     return {
    152.         x: e.pageX,
    153.         y: e.pageY
    154.     };     
    155.  
    156. }
    157. /**
    158.  * Function generates unique id
    159.  */    
    160. var getUID = function(){
    161.     var id = 0;
    162.     return function(){
    163.         return 'ValumsAjaxUpload' + id++;
    164.     }
    165. }();
    166.  
    167. function fileFromPath(file){
    168.     return file.replace(/.*(\/|\\)/, "");          
    169. }
    170.  
    171. function getExt(file){
    172.     return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
    173. }          
    174.  
    175. // Please use AjaxUpload , Ajax_upload will be removed in the next version
    176. Ajax_upload = AjaxUpload = function(button, options){
    177.     if (button.jquery){
    178.         // jquery object was passed
    179.         button = button[0];
    180.     } else if (typeof button == "string" && /^#.*/.test(button)){                  
    181.         button = button.slice(1);              
    182.     }
    183.     button = get(button);  
    184.    
    185.     this._input = null;
    186.     this._button = button;
    187.     this._disabled = false;
    188.     this._submitting = false;
    189.     // Variable changes to true if the button was clicked
    190.     // 3 seconds ago (requred to fix Safari on Mac error)
    191.     this._justClicked = false;
    192.     this._parentDialog = d.body;
    193.    
    194.     if (window.jQuery && jQuery.ui && jQuery.ui.dialog){
    195.         var parentDialog = jQuery(this._button).parents('.ui-dialog');
    196.         if (parentDialog.length){
    197.             this._parentDialog = parentDialog[0];
    198.         }
    199.     }          
    200.                    
    201.     this._settings = {
    202.         // Location of the server-side upload script
    203.         action: 'upload.php',          
    204.         // File upload name
    205.         name: 'userfile',
    206.         // Additional data to send
    207.         data: {},
    208.         // Submit file as soon as it's selected
    209.         autoSubmit: true,
    210.         // The type of data that you're expecting back from the server.
    211.         // Html and xml are detected automatically.
    212.         // Only useful when you are using json data as a response.
    213.         // Set to "json" in that case.
    214.         responseType: false,
    215.         // When user selects a file, useful with autoSubmit disabled           
    216.         onChange: function(file, extension){},                 
    217.         // Callback to fire before file is uploaded
    218.         // You can return false to cancel upload
    219.         onSubmit: function(file, extension){},
    220.         // Fired when file upload is completed
    221.         // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
    222.         onComplete: function(file, response) {}
    223.     };
    224.  
    225.     // Merge the users options with our defaults
    226.     for (var i in options) {
    227.         this._settings[i] = options[i];
    228.     }
    229.    
    230.     this._createInput();
    231.     this._rerouteClicks();
    232. }
    233.            
    234. // assigning methods to our class
    235. AjaxUpload.prototype = {
    236.     setData : function(data){
    237.         this._settings.data = data;
    238.     },
    239.     disable : function(){
    240.         this._disabled = true;
    241.     },
    242.     enable : function(){
    243.         this._disabled = false;
    244.     },
    245.     // removes ajaxupload
    246.     destroy : function(){
    247.         if(this._input){
    248.             if(this._input.parentNode){
    249.                 this._input.parentNode.removeChild(this._input);
    250.             }
    251.             this._input = null;
    252.         }
    253.     },             
    254.     /**
    255.      * Creates invisible file input above the button
    256.      */
    257.     _createInput : function(){
    258.         var self = this;
    259.         var input = d.createElement("input");
    260.         input.setAttribute('type', 'file');
    261.         input.setAttribute('name', this._settings.name);
    262.         var styles = {
    263.             'position' : 'absolute'
    264.             ,'margin': '-5px 0 0 -175px'
    265.             ,'padding': 0
    266.             ,'width': '220px'
    267.             ,'height': '30px'
    268.             ,'fontSize': '14px'                            
    269.             ,'opacity': 0
    270.             ,'cursor': 'pointer'
    271.             ,'display' : 'none'
    272.             ,'zIndex' :  2147483583 //Max zIndex supported by Opera 9.0-9.2x
    273.             // Strange, I expected 2147483647                  
    274.         };
    275.         for (var i in styles){
    276.             input.style[i] = styles[i];
    277.         }
    278.        
    279.         // Make sure that element opacity exists
    280.         // (IE uses filter instead)
    281.         if ( ! (input.style.opacity === "0")){
    282.             input.style.filter = "alpha(opacity=0)";
    283.         }
    284.                            
    285.         this._parentDialog.appendChild(input);
    286.  
    287.         addEvent(input, 'change', function(){
    288.             // get filename from input
    289.             var file = fileFromPath(this.value);   
    290.             if(self._settings.onChange.call(self, file, getExt(file)) == false ){
    291.                 return;            
    292.             }                                                      
    293.             // Submit form when value is changed
    294.             if (self._settings.autoSubmit){
    295.                 self.submit();                     
    296.             }                      
    297.         });
    298.        
    299.         // Fixing problem with Safari
    300.         // The problem is that if you leave input before the file select dialog opens
    301.         // it does not upload the file.
    302.         // As dialog opens slowly (it is a sheet dialog which takes some time to open)
    303.         // there is some time while you can leave the button.
    304.         // So we should not change display to none immediately
    305.         addEvent(input, 'click', function(){
    306.             self.justClicked = true;
    307.             setTimeout(function(){
    308.                 // we will wait 3 seconds for dialog to open
    309.                 self.justClicked = false;
    310.             }, 3000);          
    311.         });    
    312.        
    313.         this._input = input;
    314.     },
    315.     _rerouteClicks : function (){
    316.         var self = this;
    317.    
    318.         // IE displays 'access denied' error when using this method
    319.         // other browsers just ignore click()
    320.         // addEvent(this._button, 'click', function(e){
    321.         //   self._input.click();
    322.         // });
    323.                
    324.         var box, dialogOffset = {top:0, left:0}, over = false;                         
    325.         addEvent(self._button, 'mouseover', function(e){
    326.             if (!self._input || over) return;
    327.             over = true;
    328.             box = getBox(self._button);
    329.                    
    330.             if (self._parentDialog != d.body){
    331.                 dialogOffset = getOffset(self._parentDialog);
    332.             }  
    333.         });
    334.        
    335.    
    336.         // we can't use mouseout on the button,
    337.         // because invisible input is over it
    338.         addEvent(document, 'mousemove', function(e){
    339.             var input = self._input;           
    340.             if (!input || !over) return;
    341.            
    342.             if (self._disabled){
    343.                 removeClass(self._button, 'hover');
    344.                 input.style.display = 'none';
    345.                 return;
    346.             }  
    347.                                        
    348.             var c = getMouseCoords(e);
    349.  
    350.             if ((c.x >= box.left) && (c.x <= box.right) &&
    351.             (c.y >= box.top) && (c.y <= box.bottom)){          
    352.                 input.style.top = c.y - dialogOffset.top + 'px';
    353.                 input.style.left = c.x - dialogOffset.left + 'px';
    354.                 input.style.display = 'block';
    355.                 addClass(self._button, 'hover');               
    356.             } else {       
    357.                 // mouse left the button
    358.                 over = false;
    359.                 if (!self.justClicked){
    360.                     input.style.display = 'none';
    361.                 }
    362.                 removeClass(self._button, 'hover');
    363.             }          
    364.         });        
    365.            
    366.     },
    367.     /**
    368.      * Creates iframe with unique name
    369.      */
    370.     _createIframe : function(){
    371.         // unique name
    372.         // We cannot use getTime, because it sometimes return
    373.         // same value in safari :(
    374.         var id = getUID();
    375.        
    376.         // Remove ie6 "This page contains both secure and nonsecure items" prompt
    377.         // http://tinyurl.com/77w9wh
    378.         var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
    379.         iframe.id = id;
    380.         iframe.style.display = 'none';
    381.         d.body.appendChild(iframe);        
    382.         return iframe;                     
    383.     },
    384.     /**
    385.      * Upload file without refreshing the page
    386.      */
    387.     submit : function(){
    388.         var self = this, settings = this._settings;
    389.                    
    390.         if (this._input.value === ''){
    391.             // there is no file
    392.             return;
    393.         }
    394.                                        
    395.         // get filename from input
    396.         var file = fileFromPath(this._input.value);        
    397.  
    398.         // execute user event
    399.         if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
    400.             // Create new iframe for this submission
    401.             var iframe = this._createIframe();
    402.            
    403.             // Do not submit if user function returns false                                    
    404.             var form = this._createForm(iframe);
    405.             form.appendChild(this._input);
    406.            
    407.             form.submit();
    408.            
    409.             d.body.removeChild(form);              
    410.             form = null;
    411.             this._input = null;
    412.            
    413.             // create new input
    414.             this._createInput();
    415.            
    416.             var toDeleteFlag = false;
    417.            
    418.             addEvent(iframe, 'load', function(e){
    419.                    
    420.                 if (// For Safari
    421.                     iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
    422.                     // For FF, IE
    423.                     iframe.src == "javascript:'<html></html>';"){                      
    424.                    
    425.                     // First time around, do not delete.
    426.                     if( toDeleteFlag ){
    427.                         // Fix busy state in FF3
    428.                         setTimeout( function() {
    429.                             d.body.removeChild(iframe);
    430.                         }, 0);
    431.                     }
    432.                     return;
    433.                 }              
    434.                
    435.                 var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;
    436.  
    437.                 // fixing Opera 9.26
    438.                 if (doc.readyState && doc.readyState != 'complete'){
    439.                     // Opera fires load event multiple times
    440.                     // Even when the DOM is not ready yet
    441.                     // this fix should not affect other browsers
    442.                     return;
    443.                 }
    444.                
    445.                 // fixing Opera 9.64
    446.                 if (doc.body && doc.body.innerHTML == "false"){
    447.                     // In Opera 9.64 event was fired second time
    448.                     // when body.innerHTML changed from false
    449.                     // to server response approx. after 1 sec
    450.                     return;            
    451.                 }
    452.                
    453.                 var response;
    454.                                    
    455.                 if (doc.XMLDocument){
    456.                     // response is a xml document IE property
    457.                     response = doc.XMLDocument;
    458.                 } else if (doc.body){
    459.                     // response is html document or plain text
    460.                     response = doc.body.innerHTML;
    461.                     if (settings.responseType && settings.responseType.toLowerCase() == 'json'){
    462.                         // If the document was sent as 'application/javascript' or
    463.                         // 'text/javascript', then the browser wraps the text in a <pre>
    464.                         // tag and performs html encoding on the contents.  In this case,
    465.                         // we need to pull the original text content from the text node's
    466.                         // nodeValue property to retrieve the unmangled content.
    467.                         // Note that IE6 only understands text/html
    468.                         if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){
    469.                             response = doc.body.firstChild.firstChild.nodeValue;
    470.                         }
    471.                         if (response) {
    472.                             response = window["eval"]("(" + response + ")");
    473.                         } else {
    474.                             response = {};
    475.                         }
    476.                     }
    477.                 } else {
    478.                     // response is a xml document
    479.                     var response = doc;
    480.                 }
    481.                                                                            
    482.                 settings.onComplete.call(self, file, response);
    483.                        
    484.                 // Reload blank page, so that reloading main page
    485.                 // does not re-submit the post. Also, remember to
    486.                 // delete the frame
    487.                 toDeleteFlag = true;
    488.                
    489.                 // Fix IE mixed content issue
    490.                 iframe.src = "javascript:'<html></html>';";                                    
    491.             });
    492.    
    493.         } else {
    494.             // clear input to allow user to select same file
    495.             // Doesn't work in IE6
    496.             // this._input.value = '';
    497.             d.body.removeChild(this._input);               
    498.             this._input = null;
    499.            
    500.             // create new input
    501.             this._createInput();                       
    502.         }
    503.     },     
    504.     /**
    505.      * Creates form, that will be submitted to iframe
    506.      */
    507.     _createForm : function(iframe){
    508.         var settings = this._settings;
    509.        
    510.         // method, enctype must be specified here
    511.         // because changing this attr on the fly is not allowed in IE 6/7      
    512.         var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
    513.         form.style.display = 'none';
    514.         form.action = settings.action;
    515.         form.target = iframe.name;
    516.         d.body.appendChild(form);
    517.        
    518.         // Create hidden input element for each data key
    519.         for (var prop in settings.data){
    520.             var el = d.createElement("input");
    521.             el.type = 'hidden';
    522.             el.name = prop;
    523.             el.value = settings.data[prop];
    524.             form.appendChild(el);
    525.         }          
    526.         return form;
    527.     }  
    528. };
    529. })();

    тут file выводит имя с расширением
    Код (Text):
    1.  
    2. <script type="text/javascript" >
    3.     $(function(){
    4.         var btnUpload=$('#upload');
    5.         var status=$('#status');
    6.         new AjaxUpload(btnUpload, {
    7.             action: 'upload-file.php',
    8.             name: 'uploadfile',
    9.             onSubmit: function(file, ext){
    10.                  if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
    11.                     // extension is not allowed
    12.                     status.text('Разрешены форматы: JPG, PNG или GIF');
    13.                     return false;
    14.                 }
    15.                 //картинка загрузки
    16.                 status.html('<img src="loading.gif"/>');
    17.             },
    18.             onComplete: function(file, response){
    19.                 //On completion clear the status
    20.                 status.text('');
    21.                 //Add uploaded file to list
    22.                 if(response==="success"){
    23.                     $('#files').html('<img class="img" src="./uploads/'+file+'" alt="" />');
    24.                     $('#status').text(file);
    25.                 } else{
    26.                     $('#status').text(file);
    27.                 }
    28.             }
    29.         });
    30.        
    31.     });
    32. </script>
     
  2. denis01

    denis01 Суперстар
    Команда форума Модератор

    С нами с:
    9 дек 2014
    Сообщения:
    12.227
    Симпатии:
    1.714
    Адрес:
    Молдова, г.Кишинёв
    Пользователя попросит переименовать, или на стороне сервера переименуй
     
  3. rustoke

    rustoke Новичок

    С нами с:
    20 сен 2014
    Сообщения:
    145
    Симпатии:
    0
    В исполняющем php я файл переименовываю в "1000.jpg"
    Код (Text):
    1.  
    2. <?php
    3. $name = "1000";
    4. $uploaddir = './uploads/';
    5. $file = $uploaddir . basename($_FILES['uploadfile']['name']);
    6. $file_name = $uploaddir.$name.".".substr($file, strrpos($file, '.') + 1);
    7. if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file_name)) {
    8.   echo "Файл успешно добавлен! ";
    9. } else {
    10.     echo "error";
    11. }
    12. ?>
    А в Ajax как переименовать file????
    Код (Text):
    1.  
    2.         onComplete: function(file, response){
    3.                 $('#files').html('<img class="img" src="./uploads/'+file+'" alt="" />');
     
  4. denis01

    denis01 Суперстар
    Команда форума Модератор

    С нами с:
    9 дек 2014
    Сообщения:
    12.227
    Симпатии:
    1.714
    Адрес:
    Молдова, г.Кишинёв
    '+file+' это отвечает за имя файла, попробуй заменить на 1000.jpg
     
  5. rustoke

    rustoke Новичок

    С нами с:
    20 сен 2014
    Сообщения:
    145
    Симпатии:
    0
    А если мне надо загрузить файл с расширением bmp ? file состоит из имени файла и расширения, мне нужно изменить только имя файла без расширения.. простая подстановка 1000.jpg не пойдет
     
  6. Period

    Period Новичок

    С нами с:
    29 дек 2014
    Сообщения:
    148
    Симпатии:
    1
    На стороне клиента (в JS) вы не переименуете загружаемый файл. Можете создать текстовое поле, в которое пользователь будет вводить желаемое имя файла. Но зачем разрешать пользователю чего-то там ворошить на серверной стороне. Пойдут проблемы с уникальностью имён, безопасностью и т.п. Лучше файлы называть автоматически, а в базе хранить пользовательское название файла с путём к нужному файлу.

    Если заливаете файл через ajax, то пусть сервер в ответе возвращает полный путь к загруженному файлу вместе с расширением.

    Или я задачу не понял? Что вы хотите сделать?
     
  7. rustoke

    rustoke Новичок

    С нами с:
    20 сен 2014
    Сообщения:
    145
    Симпатии:
    0

    Мне нужно переименовать изображение под ID из БД при загрузки на сервер. В исполняющем PHP ID параметр я передаю методом POST , а в AJAX не могу сообразить как.
     
  8. denis01

    denis01 Суперстар
    Команда форума Модератор

    С нами с:
    9 дек 2014
    Сообщения:
    12.227
    Симпатии:
    1.714
    Адрес:
    Молдова, г.Кишинёв
    какой id? Передавай в аргумент функции
     
  9. rustoke

    rustoke Новичок

    С нами с:
    20 сен 2014
    Сообщения:
    145
    Симпатии:
    0
    я решил вопрос регуляркой. отсеял имя от расширения
     
  10. igordata

    igordata Суперстар
    Команда форума Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.408
    Симпатии:
    1.768
    это нездоровое решение.
     
  11. Period

    Period Новичок

    С нами с:
    29 дек 2014
    Сообщения:
    148
    Симпатии:
    1
    Что значит переименовать при загрузке? Вы когда файл на сервер загружаете обязаны указать имя, с которым он на сервере сохранится. С тем же самым, с которым залили только специально сделать.

    расширение узнать просто: есть встроенная функция pathinfo(), чтобы такие вещи делать. Или хотя бы по позиции последней точки. Регулярка излишнее решение.

    А вообще лучше всего сначала проверить тип файла, чего именно вам залили: finfo_file(), а потом уже только на основе этих данных сохранять с нужным расширением по switch'у или заранее созданной таблице.