Document directory
- Configuration file:
- Util tool class:
HTML page
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> JS
$ ('# Upload-click '). uploadify ({'width': '000000', 'height': '65', 'buttontext': 'upload image', 'auto': false, // do not automatically submit 'swf ': 'images/uploadify.swf', // falsh uploads the image 'upload': 'upload. do ', // upload processing, connect to the backend 'filetypedesc': 'supported File format', // File type description 'filetypeexists ':'*. jpg ;*. jpge ;*. gif ;*. png ', // type of the uploaded file 'filesizelimmit': '10m', // maximum file size 'fileobjname': 'file', // name of the object accepted in the background, keep consistent 'formdata': {'id': 1, 'name': 'irwin'}, // test the append data 'onselectererror': function (file, errorCode, errorMsg) {// trigger alert (errorMsg);}, 'onfallback': function () {// trigger alert when flash reports an error ("Install flash control first") ;}, 'onuploadsuccess': function (file, data, response) {// trigger if ("sizeError" = data) {alert ("file size cannot exceed 10 M");} else if ("typeError" = data) {alert ("unsupported file types ");}}});
Struts code, action
Package com. rying. dms. web. action; import java. io. file; import java. io. printWriter; import javax. servlet. http. httpServletResponse; import org. apache. log4j. logger; import org. apache. struts2.ServletActionContext; import com. opensymphony. xwork2.ActionSupport; import com. rying. dms. util. uploadUtil; public class UploadAction extends ActionSupport {private static Logger logger = Logger. getLogger (UploadAction. class); private static final long serialVersionUID =-response; private File file; private String fileFileName; @ Override public String execute () {PrintWriter out = null; try {HttpServletResponse response = ServletActionContext. getResponse (); response. setContentType ("text/html; charset = UTF-8"); out = response. getWriter (); // The Path Name of the test file UploadUtil. upload ("test", file, fileFileName);} catch (Exception e) {logger. error ("upload files error", e); out. print (e. getMessage ();} return null;} public File getFile () {return file;} public void setFile (File file) {this. file = file;} public String getFileFileName () {return fileFileName;} public void setFileFileName (String fileFileName) {this. fileFileName = fileFileName ;}}
Upload the util code and configure the file:
#server pathdocBase=D:\\uploadfileType=jpg,bmp,gif,png,jpeg,doc,pdf,exe,docx,avi,mp4,mp3,rmvb,3gp,swf#the size is KBmaxSize=10240#Thumbnail paththumbnailPath=thumbnailthumbnailWidth=100thumbnailHeight=80
Util tool class:
Package COM. rying. DMS. util; import Java. AWT. image; import Java. AWT. image. bufferedimage; import Java. io. file; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. util. properties; import Java. util. UUID; import javax. imageIO. imageIO; import Org. apache. log4j. logger; import COM. rying. DMS. exception. uploadexception; import COM. rying. DMS. exception. uploadsizeeffectio N; import COM. rying. DMS. exception. uploadtypeexception; import com.sun.image.codec.jpeg. export codec; import com.sun.image.codec.jpeg. export encodeparam; import com.sun.image.codec.jpeg. required imageencoder; public class uploadutil {Private Static logger = logger. getlogger (uploadutil. class); // The constant Private Static final string size_error = "sizeerror"; Private Static final string type_error = "typ Eerror "; Private Static final string upload_error =" uploaderror "; Private Static string maxsize; Private Static string filetype; Private Static string docbase; Private Static string thumbnailpath; Private Static string thumbnailwidth; private Static string thumbnailheight;/*** Upload File util *** @ author Irwin. AI * @ throws uploadtypeexception, uploadsizeexception */public static void upload (S Tring folderpath, file, string filename) throws uploadexception, uploadtypeexception, uploadsizeexception {fileinputstream FD = NULL; fileoutputstream Fos = NULL; try {// read the configuration file FS = new fileinputstream (thread. currentthread (). getcontextclassloader (). getresource ("/"). getpath (). replace ("% 20", "") + "/upload. properties "); properties pro = new properties (); pro. load (FCM); docbase = pro. getprop Erty ("docbase"); maxsize = pro. getproperty ("maxsize"); filetype = pro. getproperty ("filetype"); thumbnailpath = pro. getproperty ("thumbnail"); thumbnailwidth = pro. getproperty ("thumbnailwidth"); thumbnailheight = pro. getproperty ("thumbnailheight"); // verify the file type string fileext = ""; // obtain the file extension if (filename. lastindexof (". ")> = 0) {fileext = filename. substring (filename. lastindexof (". ") + 1);} // verify the file type L Ogger.info ("file extend name =" + fileext + ", support file type =" + filetype); If ("," + filetype. tolowercase () + ","). indexof ("," + fileext. tolowercase () + ",") <0) {logger. warn ("file type error"); // type verification error. An exception is thrown. It is captured at the action layer. The foreground determines that the error message throw new uploadtypeexception (type_error, new uploadtypeexception ();} // verify the file size. available (); logger.info ("fi Le size = "+ (size/1024) +", Max size = "+ maxsize); If (size> integer. parseint (maxsize) * 1024) {logger. warn ("file size cannot exceed 10 m"); throw new uploadsizeexception (size_error, new uploadsizeexception ();} // create a file directory // rename the file string newfilename = UUID. randomuuid (). tostring (); // save path string savedir = docbase + "/" + folderpath; // If the directory does not exist, create file filedir = new file (savedir); If (! Filedir. exists () {filedir. mkdirs ();} // save the file to the server // file storage path string savepath = savedir + "/" + newfilename + ". "+ fileext; logger.info (" Save Path = "+ savepath); Fos = new fileoutputstream (savepath); byte buffer [] = new byte [size]; int Len = 0; while (LEN = FCM. read (buffer)> 0) {FOS. write (buffer, 0, Len);} // save the file to the database // ------------------------} catch (ioexception e) {logger. error (upload_er Ror, e); throw new uploadexception (upload_error, e);} finally {try {If (null! = FOS) {FOS. Flush (); FOS. Close () ;}if (null! = Fiis) {fiis. close () ;}} catch (ioexception e) {logger. error ("Close stream error") ;}}// create a thumbnail public static void createthumbnail (File file, string fileext) throws uploadexception {try {image IMG = ImageIO. read (File); bufferedimage image = new bufferedimage (integer. parseint (thumbnailwidth), integer. parseint (thumbnailheight), bufferedimage. type_int_rgb); image. getgraphics (). drawimage (IMG, 0, 0, integer. parseint (thumbnailwidth), integer. parseint (thumbnailheight), null); string savedir = docbase + "/" + thumbnailpath; file filedir = new file (savedir); If (! Filedir. exists () {filedir. mkdirs ();} string newfilename = file. getname (); string savepath = savedir + "/" + newfilename + ". "+ fileext; fileoutputstream Fos = new fileoutputstream (savepath); required imageencoder encoder = required codec. createjpegencoder (FOS); incluencodeparam Param = inclucodec. getdefajpegincluencodeparam (image); Param. setquality (1f, true); encoder. encode (image, Param); FOS. close ();} catch (exception e) {logger. error ("create thumbnail error. "+ E); throw new uploadexception (" create thumbnail error. "+ E );}}}
Page effect: