JQuery obtains the regular expression of the name of the uploaded file.

Source: Internet
Author: User

JQuery obtains the regular expression of the name of the uploaded file.

In Web development, file upload is often involved. When a file is uploaded, it is often necessary to verify the validity of the file. This is usually determined by a regular expression.

Method 1:

?

1

2

3

4

5

6

7

$ ('Input [type = "file"] '). on ('change', function (){

Var reg =/[^ \\\/] * [\\\/] +/g; // match the regular expression of the file name and suffix

Var name = $ (this). val (). replace (reg ,'');

Var postfix =/\. [^ \.] +/. exec (name); // get the file suffix

Var text = name. substr (0, postfix ['index']); // obtain a name without a suffix

// Detect uploaded files

});

Method 2:

The following is an example. The variable file can be a string similar to a network path. In this example, the file address passed by the object name = file is obtained.

The Code is as follows:

Var file = jQuery ("input [name = 'file']"). val ()

Var filename = file. replace (/. * (\/| \\)/,"");

Var fileExt = (/[.]/. exec (filename ))? /[^.] + $/. Exec (filename. toLowerCase ()):'';

Filename

FileExt gets the suffix

Method 3:

Most of the regular expressions found on the Internet do not consider Chinese folders and Chinese file names.

Later, I wrote one by myself. After a long journey, I follow the naming rules in windows (the file name cannot contain the following characters ://*? | "<>), Finally completed a self-considered complete regular expression:

The Code is as follows:

([A-zA-Z] :) | (//) [^ ///*/? /|/: "<>] {1,255}) + /. ([j, J] [p, P] [g, G]) | ([g, G] [I, I] [f, F])

This expression is used to determine whether the type of the uploaded file is jpg or gif. I tested it myself. No matter how the folder and file name are named, it can be correctly determined as long as it can be found through windows file management.

The above is all the content of this article. I hope you will like it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.