client-side validation of file uploads in Springmvc
The main idea of client-side verification: the use of JavaScript in the JSP page to determine the file, the completion of verification allows uploading
Verification steps: 1. File name
2. Get the suffix name of the file
3. Determine which file types are allowed to upload
4. Determine file size
5. After satisfying the condition, jump backstage to implement upload
Foreground interface (verify that the upload file is in a format that meets the requirements):
<body>
File Upload
<form action="upload01" method="POST" enctype=" multipart/form-data" onsubmit= " return tosub (); " >
Uploader Name:<input type="text" name="user_name"><br>
file:<input type="file" name="myfile" id="MyFile" >
<button> upload </button>
</form>
<script type="Text/javascript">
function tosub () {//First browser support HTML5
var myfile=document.getelementbyid ("MyFile"). Files[0];
if (myfile) {
1. File name 2. Gets the suffix name of the file 3. Determine which file types are allowed to upload 4. determine file size
var filename=myfile.name;
2. Get the suffix name of the file
var ext=filename.substring (Filename.lastindexof (".") +1);
3. Determine which file types are allowed to upload
var allowfiles=["jpg", "png", "docx", "Doc"];
var flag=false;
for (var i=0;i<allowfiles.length;i++) {
if (Ext.tolowercase () ==allowfiles[i]) {
Flag=true;
break;
}
}
if (!flag) {
Alert ("The upload file format is incorrect, the allowable format is:" +allowfiles.join ("|"));
return false;
}
4. Determine file size
var maxfileuploadsize=1024*1024*20;
if (myfile.size>maxfileuploadsize) {
Alert ("Your upload file size is:" +myfile.size+ ", greater than the specified size:" +maxfileuploadsize);
return false;
}
return true;
}Else{
Alert ("Select Upload file");
return false;
}
}
</script>
</body>
Background upload:
String Path=request.getservletcontext (). Getrealpath ("/attr/");
Create files that will be stored in the current service environment
File folder=new file (path);
if (!folder.exists ()) {
Determine if this folder exists
Folder.mkdirs ();
Create folder if not present (multiple layers of mkdirs () method can be established)
}
Determine the name of the uploaded file
String Filename=myfile.getoriginalfilename ();
. Gets the suffix name of the uploaded file, for example Jpg,docx
String ext=filenameutils. getextension (filename);
The file name of the new upload file
String newfile=New Dat E (). GetTime () + "_" +new Random (). Nextint (10000) + "." +ext;
(Above is the timestamp method)
(Another way to complete) String Newfile=uuid.randomuuid (). toString () + "." +ext
Upload completed
Myfile.transferto (new File (path+file). Separator+newfile));
return "Jsp/result";
-
-------------------------------End
Client-side validation of file uploads in Springmvc