uploadify upload and background file validation code analysis
- 2020-05-16 07:01:59
- OfStack
Background upload method
@RequestMapping(value = "/api_upload", method = RequestMethod.POST)
public @ResponseBody String upload(HttpServletRequest 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 folders
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 file name
MultipartFile mf = entity.getValue();
fileName = mf.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");// return 1 A random UUID .
String suffix = fileName.indexOf(".") != -1 ? fileName.substring(
fileName.lastIndexOf("."), fileName.length()) : null;
String newFileName = uuid + (suffix != null ? suffix : "");// Constitutes the new file name.
File uploadFile = new File(uploadFilePath+storePath + newFileName);
try {
/**
* Verify the validity of the uploaded file
*/
CommonsMultipartFile cmf =(CommonsMultipartFile)mf;
boolean isValid=CheckoutFileType.getUpFilelegitimacyFlag(cmf.getFileItem(),".jpg.gif.png.jpeg");
if(!isValid){
System.out.println(" Uploading pictures is illegal ");
return null;
}
FileCopyUtils.copy(mf.getBytes(), uploadFile);
storePath = storePath + newFileName;
} catch (IOException e) {
e.printStackTrace();
}
}
return storePath;
}
File validity 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 uploaded attachments , Check for legality On the server side, the problem of file type is judged. Therefore, the method of obtaining the file header is used.
* Read the first few bytes of the file directly to determine if the uploaded file is formatted
*/
public class CheckoutFileType {
// Record each file header and the corresponding file type
public static Map<String, String> mFileTypes = new HashMap<String, String>();
// All legal 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 that due to the text document input content is too much, when reading the file header is more variable -START **/
mFileTypes.put("0D0A0D0A", ".txt");// txt
mFileTypes.put("0D0A2D2D", ".txt");// txt
mFileTypes.put("0D0AB4B4", ".txt");// txt
mFileTypes.put("B4B4BDA8", ".txt");// The head of the file is Chinese character
mFileTypes.put("73646673", ".txt");// txt, The head of the file is in English letters
mFileTypes.put("32323232", ".txt");// txt, The file header is a number
mFileTypes.put("0D0A09B4", ".txt");// txt, The file header is a number
mFileTypes.put("3132330D", ".txt");// txt, The file header is a number
/** Note that due to the text document input content is too much, when reading the file header is more variable -END **/
mFileTypes.put("7B5C727466", ".rtf"); // diary
mFileTypes.put("255044462D312E", ".pdf");
// Video or audio
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 files
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");
}
/**
* Gets file header information based on the file's input stream
*
* @param filePath
* The 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));
}
/**
* Gets file header information based on the byte array the file is converted to
*
* @param filePath
* The file path
* @return File header information
*/
public static String getFileHeader(byte[] b) {
String value = bytesToHexString(b);
return value;
}
/**
* The file that will read the header information byte Array to string Type said The following code is used to verify the file type.
* Place the bytes in front of the array 4 A convert 16 Base string, and when you convert, you first sum 0xFF do 1 Subsum operation.
* This is because there are a lot of negative Numbers in the byte array of the entire file stream, and you can get rid of all the symbol bits in front of you,
* So that translates to theta 16 Base strings are kept at most two digits, if positive and less than 10 , so only after the transformation 1 position
* You need to fill in the front 0 The purpose of doing so is to facilitate comparison before taking out 4 The bit loop can be terminated
*
* @param src The file whose header information is to be read byte An array of
* @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++) {
// In order to 106 Base (base) 16 ) returned as an unsigned integer 1 A string representation of an integer parameter, converted to uppercase
hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
if (hv.length() < 2) {
builder.append(0);
}
builder.append(hv);
}
System.out.println(" Gets file header information :" + builder.toString());
return builder.toString();
}
/**
* Determine if the uploaded file is legal ( 1 ), the first 1 : check the file extension, (2 ), The first 2 : to check the documents MIME type .
*
* @param attachDoc
* @return boolean
*/
public static boolean getUpFilelegitimacyFlag(FileItem attachDoc,String allowType) {
boolean upFlag = false;// To be true means that the upload condition is met, while to be false means that the standard does not meet
if (attachDoc != null) {
String attachName = attachDoc.getName();
System.out.println("####### Uploaded file :" + attachName);
if (!"".equals(attachName) && attachName != null) {
/** Returns the index of the specified substring that appears on the rightmost side of this string **/
String sname = attachName
.substring(attachName.lastIndexOf("."));
/** system 1 Convert to lowercase **/
sname = sname.toLowerCase();
/** The first 1 Step: check the file extension to see if it meets the required scope **/
if (allowType.indexOf(sname) != -1) {
upFlag = true;
}
/**
* The first 2 Step: get the file header of the uploaded attachment and determine which type it belongs to , And get its extension Read the first few bytes of the file directly to determine if the uploaded file is formatted
* Prevents upload attachments from changing the extension to bypass validation
***/
if (upFlag) {
byte[] b = new 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("/////// The type of file the user uploads ///////////"
+ req_fileType);
/** The first 3 Step: check the file extension to see if it meets the required scope **/
if (req_fileType != null && !"".equals(req_fileType)
&& !"null".equals(req_fileType)) {
/** The first 4 Step: verify the uploaded file extension is within its specified scope **/
if (allowType.indexOf(req_fileType) != -1) {
upFlag = true;
} else {
upFlag = false;
}
} else {
/** Special case check , If the user uploads the extension name , Text file , Upload is allowed -START **/
if (sname.indexOf(".txt") != -1) {
upFlag = true;
} else {
upFlag = false;
}
/** Special case check , If the user uploads the extension name , Text file , Upload is allowed -END **/
}
}
}
}
return upFlag;
}
/**
* Main function for testing
*
* @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();
} 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],
delimiter:' '
});
$('#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':100,
'removeCompleted':true,
'fileTypeExts': '*.jpg;*.gif;*.png;*.jpeg;',
'fileSizeLimit':'2MB',
'fileTypeDesc': ' upload ',
'onUploadSuccess':function(file,data,response) {
if(data!=null && data.length>0){
var uploadFiles=$("#tickets").val().split(',');
var uploadFileSize=uploadFiles.length;
if(uploadFileSize>5){
layer.msg(" Up to upload 5 image ");
return ;
}
addTickets(data);
/* layer.ready(function(){
layer.photos({
photos: '#imgShow',
shade:0.5
});
}); */
}else{
layer.msg(" Upload failed ");
}
isUploadSuccess=true;
},
'onUploadError':function(file, errorCode, errorMsg, errorString) {
if(errorString.indexOf('The upload limit has been reached')){
layer.msg(errorString);
}
},
'onSelect' : function(file) {
//alert('The file ' + file.name + ' was added to the queue.');
isUploadSuccess=false;
},
'onSelectError' : function(file, errorCode, errorMsg){
switch(errorCode){
case -110:
layer.msg(" The file size is over 2M");
break;
case -100:
layer.msg(" Up to upload 5 image ");
break;
default:
layer.msg(errorMsg);
}
},
'onDialogClose' : function(queueData) {
var uploadFiles=$("#tickets").val().split(',');
var uploadFileSize=uploadFiles.length;
if(uploadFileSize>5){
layer.msg(" Up to upload 5 image ");
queueData.filesSelected=0
return false;
}
}
});
onQuery();
});