» » Tips about the file upload

 

Tips about the file upload

Author: bamboo06 on 16-11-2017, 22:45, views: 216

10
File upload WEB development in a wide range of applications, we often send microblogging, send micro-channel circle of friends have used the picture upload function. File upload refers to the process of uploading local images, videos, audio files to the server for other users to browse or download. Today, I talk to you about the common file (picture) upload methods and points to deal with.
Tips about the file upload


Form upload
This is the traditional form of form upload, use form form input [type = "file"] control, you can open the system file selection dialog box, so as to achieve the purpose of selecting files and upload, it is multi-browser compatible, it is Is the most commonly used web developers a way to upload files.

The form code is as follows:
<form method="post" action="http://uploadUrl" enctype="multipart/form-data"> 
    <input name="file" type="file" accept="image/gif,image.jpg" /> 
    <input name="token" type="hidden" /> 
    <input type="submit" value="submit" />  
</form>


Here are a few key points for the form upload:
method = "post": Submit data using post method
enctype = "multipart / form-data": The multipart format upload file, the request header will display Content-Type: multipart / form-data; boundary = ---- WebKitFormBoundaryzr34cwJ67R95KQC9
action: indicates the address of the server to upload
type = "file": Use input file control upload
If it is a multi-file bulk upload, you can set the name property of input [type = "file"] to something like: name = "file []"
The accept property is a new HTML5 property that specifies the types of files that can be submitted via file upload
The trigger for the upload can be: onchange triggered by input [type = "file"], or by a separate button onclick to commit the entire form, with input [type = "hidden"] and some other Parameters, such as Token source verification and more.

2 Ajax no refresh upload
Ajax no way to refresh the upload, essentially the same as the form upload, just submit the contents of the form submitted by ajax, and the front-end request results after the return of the display results, do not like direct form upload as refresh and jump page. Here, we use jQuery as the base for manipulating the DOM and creating js submitted by ajax.

html code fragment is as follows:
<form> 
    <input id="file" name="file" type="file" /> 
    <input id="token" name="token" type="hidden" /> 
</form>

javascript code snippet is as follows:
$("#file").on("change", function(){ 
  var formData = new FormData(); 
  formData.append("file", $("#file")[0].files); 
  formData.append("token", $("#token").val()); 
  $.ajax({ 
      url: "http://uploadUrl", 
      type: "POST", 
      data: formData, 
      processData: false, 
      contentType: false, 
      success: function(response){ 
              //  According to the return result to specify the interface operation
      } 
  }); 
});

We use the file control change to trigger the upload event, of course, you can also use a button to trigger the form to submit. When submitting the data, I used the FormData object to send the binary file. The append () method provided by the FormData constructor can be added to the server as an XMLHttpRequest instance parameter with some additional parameters attached directly to the binary file.

Using the ajax method provided by jQuery to send a binary file requires the addition of two parameters:
processdata: false / / Do not serialize the data parameter, the default is true
contentType: false / / Do not set the Content-Type request header, because the file data is encoded as multipart / form-data
Ajax upload can refer to the site article: PHP + jQuery + Ajax multiple image upload

Flash upload
Many times the demand for upload shows the progress of the upload, interrupt the upload process, upload large file fragments, etc., then the traditional form upload is difficult to achieve these features, resulting in the use of Flash upload method, which uses Flash as an intermediate agent Layer, instead of client to server communication, in addition, it also has more control over the client's file selection than the input [type = "file"] is much larger.

Here I use the jQuery packaged uploadify plug-in to demonstrate, the general type of plug-in comes with the upload Flash file, because the data returned with the server and display with the client's interaction, are Flash file interface Docking to docking.
<div id="file_upload"></div>

html part is very simple, set aside a hook, the plug-in will create a Flash object within this node, and also with the creation of the upload progress, cancel the control and multi-file queue display interface.
$(function() { 
  $("#file_upload").uploadify({ 
      auto: true, 
      method: "Post", 
      width: 120, 
      height: 30, 
      swf: './uploadify.swf', 
      uploader: 'http://uploadUrl', 
      formData: { 
          token: $("#token").val() 
      }, 
      fileObjName: "file", 
      onUploadSuccess: function(file, data, response){ 
          //According to the return result to specify the interface operation
      } 
  }); 
});

About jQuery.uploadify You can visit: . It is noteworthy that the flash is not suitable for mobile applications, a better solution is to use flash + html5 to solve the compatibility issue of the platform.

Screenshot paste upload
We found that there are a lot of upload applications have been provided screenshot paste upload function, such as WebUploader, it supports QQ screenshot and then paste the upload.

First of all, the core idea of the screenshot paste upload is to monitor the paste event, and then get the data in the clipboard, if it is a picture, the upload event is triggered.

The code snippet is as follows:
$("textarea").on("paste", function(e){ 
   e.stopPropagation(); 
   var self = this; 
   var clipboardData = e.originalEvent.clipboardData; 
   if (clipboardData.items.length <= 0) { 
       return; 
   } 
   var file = clipboardData.items[0].getAsFile(); 
   if (!file) { 
       return; 
   } 
   var formData = new FormData(); 
   formData.append("file", file); 
   formData.append("token", $("#token").val()); 
   $.ajax({ 
       url: "http://uploadUrl", 
       type: "POST", 
       data: formData, 
   }).done(function(response) { 
       // operation by ur idea 
   }); 
   e.preventDefault(); 
});

As can be seen from the above code, the upload process is the same, mainly to obtain the file. When paste (right paste / ctrl + v) operation, trigger the clipboard event 'paste', get the contents from the system clipboard, and system clipboard data stored in different browser in different locations:

IE kernel: windows.clipboardData
Other: e.originalEvent.clipboardData
You can read Image upload and clipping applications by Croppie to learn the method.

Drag and drop upload
Drag-and-drop method, support fewer browsers, because it uses two new HTML5 attributes (API) a Drag and Drop, a File API.

Upload domain monitoring drag and drop three events: dragEnter, dragOver and drop, respectively, corresponding to the drag and drop, drag and release of the three operating mechanism, of course, you can also monitor the dragLeave event.

HTML5 File API provides a FileList interface, it can drag the event e.dataTransfer.files to pass the file information for local file list information.

The File API is just a draft in the HTML5 specification. In the W3C draft, a File object contains only read-only attributes such as file name, file type, and file size. However, some browsers provide an object named FileReader outside the draft to read the contents of the file and monitor the read status. The methods it provides are readAsBinaryString, readAsDataURL, readAsText, "abort" and so on.

The code snippet is as follows:
// dragenter 
$("#textarea").on("dragenter", function(e){ 
    e.preventDefault(); 
}); 
// dragover 
$("#textarea").on("dragover", function(e){ 
    e.preventDefault(); 
}); 
// drop 
$("#textarea").on("drop", function(e){ 
    e.stopPropagation(); 
    e.preventDefault(); 
    var files = e.originalEvent.dataTransfer.files; 
    _.each(files, function(file) { 
        if (!/^image*/.test(file.type)) { 
          return; 
        } 
        var fileReader = new FileReader(); 
        fileReader.onload = function() { 
          //uploadFile(file); 
        }; 
        fileReader.readAsDataURL(file); 
    }); 
});

Drag and drop a few key points in the upload process:

After the drop event is triggered by e.dataTransfer.files get a list of drag files in jQuery e.originalEvent.dataTransfer.files
Drag-and-drop upload only supports images, and file.type in the file object identifies the file type.
Since it may be multi-image drag and drop, so you can traverse the image upload, use Underscore each method.
Here readAsDataURL reads the contents of the file as a binary file, you can also convert it to Base64 upload method, but there is http protocol inside non-binary data upload size limit of 2M.
The process of uploading is the same as before, ie creating a FormData object and initiating an Ajax request.

Upload photos
Camera upload can be a camera on a PC Camera upload can also be mobile phones and other mobile device photo upload. The most common photo upload on mobile phones is that we use WeChat to send photos.

Phone to achieve photo upload code:
<input type=file accept="image/*">  
<input type=file accept="video/*">

ios have pictures, videos, select the local image features, select only part of the android local image features.

Upload and security
File upload must be done file security, in addition to the front of the necessary validation, such as file type, suffix, size and other validation, the important thing is to do in the background security strategy.

Here I cite a few notes:

Background need to document type, size, source verification
Define an .htaccess file that will only allow access to the file with the specified extension.
Generate a random file name for the uploaded file, plus the previously generated file name extension.
Set the upload directory permissions to prevent malicious people bypassing the image extension of malicious attacks, the possibility of rejecting script execution.

Tags: file, upload

Category: PHP Scripts / Javascript / Plugins / Internet

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
<
  • 0 Comments
  • 0 Articles
17 November 2017 16:34

ValerieStoner

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
The people who are working in the field of the website know the importance of the PHP. This software is working so well and has the good features and you can check out essay company review for the best info. You give more attention to the function of this software which is good.

<
  • 1 Comment
  • 0 Articles
20 November 2017 21:58

sharlynharville

Reply
  • Group: Members
  • РRegistered date: 20.11.2017
  • Status: Currently Offline
 
Thanks for the Tips Really I was seeking about because I'm confused how can i upload a picture I have a Custom Essay Services website so i face problem every time and it takes a long time maybe it will save my time.

<
  • 0 Comments
  • 0 Articles
23 November 2017 09:12

RimmaZura

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Всем Хелло! народ кто любит игать в игры подскажите откопала эту тему:
Как играть в современные игрушки без скачивания и установки на пК посредством сервис Playkey
а так же нашла Генератор промокодов для сервиса Playkey ТУТ видео
Кто тестил сервис и Генератор отпишите в личку стоит ли заморочки!

Alanja: Генератор промо-кодов не знаю, я пользуюсь патчем
Патч для бесплатного пользования сервисом скачивай здесь.
Видео по установке и настройке патча смотри тут.
Всё работает! А за ссылки в коментах админ goocode.net может Забанить.

<
  • 0 Comments
  • 0 Articles
24 November 2017 02:30

Antonio kim

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
i'm believe your post because your all through are precious infect additionally Eminem it’s my favorite singer anyhow i hope you share more interesting article on this internet site. So, i'm bookmarked your weblog. Jon Snow Game Of Thrones Jacket

<
  • 0 Comments
  • 0 Articles
27 November 2017 22:48

Kristine Stevart

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
I just idea it might be a plan to post encase any other person was having issues investigating yet I am somewhat uncertain on the off chance that I am permitted to put names and addresses on here. Custom Essay Help Service

<
  • 0 Comments
  • 0 Articles
2 December 2017 04:15

Kristine Nardone

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Thank you for the information cheap reliable essay writing service you post and hopefully useful to readers

<
  • 0 Comments
  • 0 Articles
3 December 2017 20:20

Keithler

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
<a href="https://www.carbatterysale.review/car-audio-battery-terminal/tvr-spee
d-eight-1989-1992-banner-power-bull-70ah-battery-electrical-replace-part.php&quo
t;>Tvr Speed Eight 1989-1992 Banner Power Bull 70Ah Battery Electrical Replace Part</a>
Renault 11 B/C37 1986-1988 Bosch S4 Battery 60Ah Electrical System Replace Part
<a href="https://www.newcarbattery.download/car-battery-cables/fiat-stilo-192-
2001-2006-vetech-battery-55ah-electrical-system-replacement-part.php">Fi
at Stilo 192 2001-2006 Vetech Battery 55Ah Electrical System Replacement Part</a>
Volvo V90 1997-1998 Banner Starting Bull 55Ah Battery Electrical Replace Part
<a href="https://www.buycarbattery.cricket/electric-car-battery-pack/vw-sciroc
co-137-2008-2016-bosch-s4-battery-60ah-electrical-system-replace-part.php"&
gt;VW Scirocco 137 2008-2016 Bosch S4 Battery 60Ah Electrical System Replace Part</a>
Fiat Bravo Mk1 1995-2001 Vetech Battery 55Ah Electrical System Replacement Part
<a href="https://www.carbatteryprice.racing/car-battery-booster-jump-starter/r
over-075-12volt-car-battery-free-delivery-and-fitting-in-the-local-area.php"
;>ROVER 075 12Volt Car Battery FREE DELIVERY AND FITTING IN THE LOCAL AREA</a>
Toyota Corolla Liftback E10 E11 E9 1987-2002 Bosch S4 Battery 95Ah

<
  • 0 Comments
  • 0 Articles
4 December 2017 17:16

JamesExpag

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
get viagra at a discount
<a href="http://viagrajnmeo.com/#">viagra without a prescription</a>
viagra for dogs online
viagra without a doctor’s prescription
viagra online kaufen zoll

<
  • 0 Comments
  • 0 Articles
4 December 2017 19:25

Robertvar

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
vendita viagra generico on line
<a href="http://viagrajnmeo.com/#">viagra without a doctor</a>
bifort sildenafil 25 mg
viagra without a doctor's prescription
cheap cialis viagra

<
  • 0 Comments
  • 0 Articles
Today, 15:50

Katrinaanisa

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
pay day loans
cash advance loans
<a href="https://smajloans.com/">payday advance</a>
payday loans no credit check


Add comments

Name:*
E-Mail:
Comment:
Bold Italic Underline Strike | Align left Center Align right | Insert smilies Insert link URLInsert protected URL Select color | Add Hidden Text Insert Quote Convert selected text from selection to Cyrillic (Russian) alphabet Insert spoiler
Security Code: *