HTML Ajax upload file Limits file type and file size

Source: Internet
Author: User

Html

<input type= "file" Name= "Excel" Id= "Excel_input" accept= ". Doc,.docx,.xls,.xlsx" onchange = "uploadfile (th is,1) "/>

Js

  

function Getfiletype (FilePath) {

Gets the suffix name of the file
var startIndex = Filepath.lastindexof (".");
if (startIndex! =-1)
Return filepath.substring (startindex+1, filepath.length);
else return "";
}
function UploadFile (obj, type) {
var FilePath = $ ("#excel_input"). Val ();

if (""! = FilePath) {
var fileType = Getfiletype (FilePath);
Determine if the uploaded attachment is a Word file and an Excel file
if ("Doc"!=filetype && "docx"!=filetype && "xls"!=filetype && "xlsx"!=filetype) {
$ ("#excel_input"). Val ("");
Alert ("Please upload form file");
}
else{
Get attachment size (in KB)
var fileSize = document.getElementById ("Excel_input"). files[0].size/1024;
if (FileSize > 500) {
Alert ("File size cannot exceed 500KB");
$ ("#excel_input"). Val ("");
} else{
var formData = new FormData ();

var name = $ ("#excel_input"). Val ();

Formdata.append ("Excel", $ ("#excel_input") [0].files[0]); Get the contents of a file

Formdata.append ("name", name); Path to the file

$.ajax ({
Type: ' POST ',

Processdata:false,//does not process the sent data because the data value is a Formdata object and does not need to be processed
Contenttype:false,//Do not set Content-type request header
URL: "/admin/user/addusers",//fill in your own way
Data:formdata,
DataType: ' json ',//return value type is generally set to JSON
Success:function (data) {//server successful response handler function
Alert ("Upload success");
Window.location.reload ();//Refresh the page after uploading successfully
},
Error:function (data) {
Alert ("Server Exception");
}
});
}
}
}

return false;
}

HTML Ajax upload file Limits file type and file size

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.