Uploadify upload and background file Legality verification of code analysis _java

Source: Internet
Author: User
Tags uuid access database

Background upload method

@RequestMapping (value = "/api_upload", method = requestmethod.post) public @ResponseBody String upload (httpservletreque 
St Request,httpservletresponse Response) {//Get upload path String uploadfilepath=parameterconstants.upload_file_path; 
String storepath= ""; 
Multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request; 
Gets the foreground pass value string[] folders = multipartrequest.getparametervalues ("path"); 
String folder = ""; 
if (folders!= null) {folder = Folders[0]; 
storepath+=folder+ "/"; 
} map<string, multipartfile> filemap = Multipartrequest.getfilemap (); 
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyymm"); 
String ymd = Sdf.format (New Date ()); 
Storepath + = Ymd + "/"; 
Create folder File File = new file (Uploadfilepath+storepath); 
if (!file.exists ()) {file.mkdirs (); 
String fileName = null; 
String path = null; For (map.entry<string, multipartfile> entity:fileMap.entrySet ()) {//upload filename multipartfile MF = entity.getvalue () 
; FileName = Mf.getoriGinalfilename (); 
String uuid = Uuid.randomuuid (). toString (). ReplaceAll ("\\-", "");//returns a random uuid. String suffix = filename.indexof (".")!=-1? 
Filename.substring (Filename.lastindexof ("."), Filename.length ()): null; 
String NewFileName = uuid + (suffix!= null? suffix: "");//Make up the new file name. 
File UploadFile = new file (Uploadfilepath+storepath + newfilename); 
try {/** * Verify the legality of the upload file */commonsmultipartfile CMF = (commonsmultipartfile) MF; 
Boolean Isvalid=checkoutfiletype.getupfilelegitimacyflag (Cmf.getfileitem (), ". Jpg.gif.png.jpeg"); 
if (!isvalid) {System.out.println ("Upload picture is illegal"); 
return null; 
} filecopyutils.copy (Mf.getbytes (), uploadfile); 
Storepath = Storepath + newfilename; 
catch (IOException e) {e.printstacktrace (); 
} return Storepath; }

file legality validation class

Package com.kaiyuan.common.util; 
Import Java.io.FileInputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import Java.util.HashMap; 
Import Java.util.Map; 
Import Org.apache.commons.fileupload.FileItem; /** * @Description: Processing upload attachments, verify the legality of the file type in the server to determine the problem, so the way to get the file header, * directly read the first few bytes of the file to determine whether the upload file conforms to the format * * public class Checkoutfile 
Type {///log individual header information and corresponding file type public static map<string, string> mfiletypes = new hashmap<string, string> (); 
All valid file suffixes public static String Res_filetype = ". Jpg.gif.png.jpeg"; 
static {//Images mfiletypes.put ("Ffd8ffe0", ". jpg"); 
Mfiletypes.put ("89504E47", ". png"); 
Mfiletypes.put ("47494638", ". gif"); 
Mfiletypes.put ("49492a00", ". tif"); 
Mfiletypes.put ("424D", ". bmp"); 
PS and CAD mfiletypes.put ("38425053", ". psd"); Mfiletypes.put ("41433130", ". dwg"); 
CAD mfiletypes.put ("252150532d41646f6265", ". PS"); Office document class Mfiletypes.put ("D0cf11e0", ". Doc"); ppt, doc, xls mfiletypes.put ("504b0304", ". docx");//pptx, docx, xlsx/** Note Because the text document input content is too much, then read the file header more changeable-start **/mfiletypes.put ("0d0a0d0a", "txt"); txt mfiletypes.put ("0d0a2d2d", "txt"); /txt mfiletypes.put ("0d0ab4b4", ". txt");/txt mfiletypes.put ("B4b4bda8", ". txt");/file head is Kanji mfiletypes.put ("73646673 ",". txt ");/txt, the file head is English letter mfiletypes.put (" 32323232 "," TXT "),/txt, the file header content is a digital mfiletypes.put (" 0d0a09b4 "," txt "); 
TXT, file head content for digital mfiletypes.put ("3132330D", "txt");/txt, file head content for digital/** Note because the text document input content too much, then read the file head more changeable-end **/ Mfiletypes.put ("7b5c727466", ". rtf"); 
Journal mfiletypes.put ("255044462d312e", ". pdf"); 
Video or audio class Mfiletypes.put ("3026b275", ". wma"); 
Mfiletypes.put ("57415645", ". wav"); 
Mfiletypes.put ("41564920", ". avi"); 
Mfiletypes.put ("4d546864", ". Mid"); 
Mfiletypes.put ("2e524d46", ". RM"); 
Mfiletypes.put ("000001BA", ". mpg"); 
Mfiletypes.put ("000001b3", ". mpg"); 
Mfiletypes.put ("6d6f6f76", ". mov"); 
Mfiletypes.put ("3026b2758e66cf11", ". asf"); 
Compressed Package Mfiletypes.put ("52617221", ". rar"); 
Mfiletypes.put ("1f8b08", ". gz"); program File MfilEtypes.put ("3c3f786d6c", ". xml"); 
Mfiletypes.put ("68746d6c3e", ". html"); 
Mfiletypes.put ("7061636B", ". Java"); 
Mfiletypes.put ("3c254020", ". jsp"); 
Mfiletypes.put ("4d5a9000", ". exe"); Mfiletypes.put ("44656c69766572792d646174653a", ". eml"); 
Mail Mfiletypes.put ("5374616e64617264204a", ". mdb");/Access database file Mfiletypes.put ("46726f6d", ". mht"); 
Mfiletypes.put ("4d494d45", ". MHTML");  /** * Get header information from file input stream * * @param filePath * File path * @return file header information/public static String Getfiletype (InputStream 
IS) {byte[] b = new Byte[4]; 
if (is!= null) {try {is.read (b, 0, b.length); 
catch (IOException e) {e.printstacktrace (); 
} return Mfiletypes.get (GetFileHeader (b)); /** * The byte array converted from the file gets the header information * * @param filePath * File path * @return file header information/public static String GetFileHeader (byte[ 
] (b) {String value = bytestohexstring (b); 
return value; 
/** * Converting a byte array of files that will read header information to a string indicates that the following code is the method used to validate the file type. * Converts the first four bits of a byte array into a 16 string, and the conversion is done first with the 0xFF. * This is because, the entire file streambyte array, many of which are negative, after the operation, you can remove the previous symbol bits, * This converted to a 16-character string to retain a maximum of two digits, if the positive number is less than 10, then only one after the conversion, * need to complement 0 in the front, the purpose is to facilitate comparison, The first four digits of the loop can be terminated. * @param src byte array of files to read header information * @return file header information/private static String bytestohexstring (byte[] src 
) {StringBuilder builder = new StringBuilder (); 
if (src = null | | | src.length <= 0) {return null; 
} String HV; for (int i = 0; i < src.length i++) {//returns the string representation of an integer parameter as a 16-in (Cardinal 16) unsigned integer and converts to uppercase HV = integer.tohexstring (src[i) 
& 0xFF). toUpperCase (); 
if (Hv.length () < 2) {builder.append (0); 
} builder.append (HV); 
System.out.println ("Get File header information:" + builder.tostring ()); 
return builder.tostring (); 
/** * To determine whether the uploaded file is legal (i), first: Check the file extension, (ii), second: Check the file MIME type. * * @param Attachdoc * @return Boolean/public static Boolean Getupfilelegitimacyflag (Fileitem attachdoc,string allo  
Wtype) {Boolean upflag = false;//is true to match the upload condition, the false table does not conform to if (Attachdoc!= null) {String attachname = Attachdoc.getname (); System.out.println ("###### #上传的文件:" + ATtachname); if (! "". Equals (attachname) && attachname!= null) {/** Returns the index of the specified substring that appears at the far right of this string **/string sname = Attachname. Substrin 
G (Attachname.lastindexof (".")); 
/** Unified conversion to lowercase **/sname = sname.tolowercase (); 
/** The first step: Check the file extension to see if it meets the required range **/if (Allowtype.indexof (sname)!=-1) {Upflag = true; /** * Second step: Get upload the file header of the attachment, judge which type, and get its extension directly read the first few bytes of the file, to determine whether the upload file conforms to the format * Prevent upload attachment change extension bypass checksum ***/if (upflag) {byte[] b = n 
EW byte[4]; 
String req_filetype = null; 
try {req_filetype = Getfiletype (Attachdoc.getinputstream ()); 
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
} System.out.println ("///////user uploaded file type///////////" + req_filetype); /** Step Three: Check the file extension to see if it meets the required range **/if (req_filetype!= null &&! "". Equals (Req_filetype) &&! " Null ". Equals (Req_filetype)) {/** Step Fourth: Verify the uploaded file name extension, within its specified range **/if (Allowtype.indexof (Req_filetype)!=-1) {Upflag = tr 
Ue 
else {Upflag = false; } else {/** Special case check, if the user uploads the extension, text file, then allow upload-stART **/if (sname.indexof (". txt")!=-1) {Upflag = true; 
else {Upflag = false; 
/** Special case Check, if the user upload extension, text file, then allow upload-end **/}}} return upflag; /** * Main function, Test * * @param args * @throws Exception/public static void main (string[] args) throws Exception {/ 
/FINAL String FileType = Getfiletype ("d:/bicp-huawei.mht"); 
FileInputStream is = null; 
String value = null; 
String FilePath = "E:/aa/c.txt"; 
try {is = new FileInputStream (FilePath); 
Byte[] B = new Byte[4]; 
Is.read (b, 0, b.length); 
Value = bytestohexstring (b); 
catch (Exception e) {} finally {if (null!= is) {try {is.close (); 
The catch (IOException e) {}}} System.out.println (value); } 
}

front-end upload JS

$ (document). Ready (function () {new Textmagnifier {inputelem: ' #bankCardNo ', align: ' top ', SplitType: [4,4,4,5,5], D 
Elimiter: "}); $ (' #file_upload '). Uploadify ({' formData ': {' path ': '/uploadfilepath ',}, ' swf ': ' ${pagecontext.request.contextpath}/ js/upload/uploadify.swf ', ' uploader ': getbasepath () + '/upload/api_upload;jsessionid=${pagecontext.session.id} ', ' Cancelimg ': ' ${pagecontext.request.contextpath}/js/upload/uploadify-cancel.png ', ' buttontext ': ' Upload ', ' auto ': true, ' Multi ': True, ' uploadlimit ': M, ' removecompleted ': true, ' filetypeexts ': ' *.jpg;*.gif;*.png;*.jpeg; ', ' Filesizelimit ': ' 2MB ', ' filetypedesc ': ' Upload ', ' onuploadsuccess ': function (file,data,response) {if (Data!=null && data.length& 
gt;0) {var uploadfiles=$ ("#tickets"). Val (). Split (', '); 
var uploadfilesize=uploadfiles.length; 
if (uploadfilesize>5) {layer.msg ("upload up to 5 photos"); 
return; 
} addtickets (data); 
/* Layer.ready (function () {Layer.photos ({photos: ' #imgShow ', shade:0.5});}); 
* *}else{layer.msg ("Upload failure"); 
} isuploadsuccess=true; }, ' Onuploaderror ': function (file, errorcode, ErrorMsg, errorstring) {if (Errorstring.indexof (' upload limit, has, been 
Reached ')) {layer.msg (errorstring); 
}, ' Onselect ': function (file) {//alert (' the file ' + File.name + ' is added to the queue. '); 
Isuploadsuccess=false; 
}, ' Onselecterror ': function (file, errorcode, errormsg) {switch (errorcode) {case-110:layer.msg ("Files larger than 2M"); 
Break 
Case-100:layer.msg ("Upload up to 5 photos"); 
Break 
Default:layer.msg (ERRORMSG); 
}, ' Ondialogclose ': function (queuedata) {var uploadfiles=$ ("#tickets"). Val (). Split (', '); 
var uploadfilesize=uploadfiles.length; 
if (uploadfilesize>5) {layer.msg ("upload up to 5 photos"); 
Queuedata.filesselected=0 return false; 
} 
} 
}); 
Onquery (); });

The above is a small set to introduce the Uploadify upload and background documents to verify the legality of the Code analysis, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.