Fileuploadcontroller.java
Import Org.json.JSONObject;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import Org.springframework.beans.factory.annotation.Value;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.multipart.MultipartFile;
Import Org.springframework.web.servlet.ModelAndView;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import java.io.*;
/** * Created by Yz.shi on 2018/3/15. * * @Controller public class Fileuploadcontroller {private static final Logger Logger = Loggerfactory.getlogger (Fileuploa
Dcontroller.class);
@Value ("${shop.back.uploadurl}") Private String uploadurl;
@Value ("${shop.back.uploaddir}") Private String Uploaddir; /** * Last file (first to temporary directory) * * @param uploadfile * @param request * @param response * @return * * @RequestMapping ("/ Uploadtempimport_backuser ") Public Modelandview Uploadtempimport (Multipartfile uploadfile, HttpServletRequest request, HttpServletResponse response) {Jsonobject JSON =
New Jsonobject ();
try {json.put ("result", false);
String originalfilename = Uploadfile.getoriginalfilename ();
String NewFileName = Fileutil.getrandomfilename (originalfilename);
String TempPath = uploaddir + "//temp//";
Fileutil.mkdirs (TempPath);
File NewFile = new file (TempPath, newfilename);
Uploadfile.transferto (NewFile);
String Streampath = uploadurl + "temp/" + newfilename;
Json.put ("FileName", NewFileName);
Json.put ("result", true);
Json.put ("FileUrl", Streampath);
catch (Exception e) {logger.error ("File upload failed:", e);
Return to New Modelandview ("/result.jsp"). AddObject ("JSON", json.tostring ());
/** * Download File * * @param modelname * @param fileName * @param response * @return * @throws IOException * * @RequestMapping ("/downbypath_backuser") public string Downbypath (string modelname, String fileName, HTtpservletresponse response) throws IOException {response.setcharacterencoding ("utf-8");
Response.setcontenttype ("Multipart/form-data");
Response.setheader ("Content-disposition", "attachment;filename=" + fileName); try {inputstream InputStream = new FileInputStream (new File (Uploaddir + file.separator + modelname + File.separa
Tor + fileName));
OutputStream OS = Response.getoutputstream ();
Byte[] B = new byte[2048];
int length;
while (length = Inputstream.read (b)) > 0) {os.write (b, 0, length);
} os.close ();
Inputstream.close ();
catch (Exception e) {logger.error ("File upload failed:", e);
return null; }
}
Shop.back.uploadDir = e:\\workspace\\shop-static\\src\\main\\webapp\\upmall\\
shop.back.uploadurl= http:// static.com/upmall/
Fileutil.java
Import Org.springframework.http.HttpHeaders;
Import Org.springframework.http.HttpStatus;
Import Org.springframework.http.MediaType;
Import org.springframework.http.ResponseEntity;
Import java.io.*;
Import java.util.ArrayList;
Import Java.util.Calendar;
Import java.util.List;
/** * Created by Yz.shi on 2018/3/15.
* * Public class Fileutil {public static String path_separate = "/"; /** * Create directory * * @param dirpath */public static void Mkdirs (String dirpath) {File dirfile
= new File (Dirpath);
if (!dirfile.exists ()) {dirfile.mkdirs ();
}/** * Delete file * * @param filePath */public static Boolean DeleteFile (String filePath) {
File File = new file (FilePath);
if (!file.exists ()) {return true;
return File.delete ();
public static Boolean deletedirectory (String dirpath) {return deletedirectory (new File (Dirpath));
}
/** * Delete files and directories * * @param file * @return/public static Boolean deletedirectory (file file) {
if (!file.exists ()) {return true;
} if (File.isdirectory ()) {file[] listfiles = File.listfiles ();
for (File childrenfile:listfiles) {fileutil.deletedirectory (childrenfile);
} return File.delete (); /** * Get a random filename * * @param realfilename * @return/public static String Getrandomfi Lename (String realfilename) {string newfilename = Calendar.getinstance (). Gettimeinmillis () + Randomutil.getnumber
Code (4);
int index = Realfilename.lastindexof (".");
if (index >= 0) {NewFileName + = realfilename.substring (index);
return newfilename; /** * Gets a new file object, exists first delete * * @param filePath * @return/public static file Getnewfile (S Tring FilePath) {File File = new file (FilePath);
if (file.exists ()) {file.delete ();
} return file; /** * Create a file, delete the file if it exists and create a new * * @param filePath file full path * @return Return the newly created file/public
Static file CreateNewFile (String filePath) {File File = new file (FilePath);
if (file.exists ()) {file.delete ();
try {file.createnewfile ();
catch (IOException e) {throw new RuntimeException (e);
} return file; /** * Generate filename with version number * * @param filename * @param * @return/public static String G
Etfileversionname (String fileName, int version) {int index = Filename.lastindexof (".");
Return filename.substring (0, index) + version + filename.substring (index); /** * Check file path exists * * @param filePath * @return/public static Boolean Checkfileexist (StRing filePath) {File File = new file (FilePath);
return file.exists (); /** * Returns the file's extension * * @param fileName * @return/public static String GetExtension (stri
ng filename) {return getextension (FileName, ""); public static string GetExtension (string filename, string ext) {if (fileName!= null && FILENAME.L
Ength () > 0) {int i = Filename.lastindexof (".");
if (i > 1 && i < (filename.length ()-1)) {return filename.substring (i + 1);
} return ext; /** * Read txt content from File * * @param pathname * @return/public static List Getlistbytxt (Str
ing pathname) {list<string> List = new arraylist<string> (); File filename = new file (pathname); To read input from the above path. TXT file inputstreamreader reader = null; Create an input stream object reader try {reader = newInputStreamReader (filename) (new FileInputStream); BufferedReader br = new BufferedReader (reader);
Create an object that turns the contents of the file into a language that the computer can read, String line = "";
line = Br.readline ();
if (stringutil.isnotnullstr) {list.add (line); While lines!= null {line = Br.readline ();//read one row of data once (Stringutil.isno
Tnullstr (line)) {List.add (line);
A catch (Exception e) {e.printstacktrace ());
} return list; /** * getresponseentity * * @param fileName * @param filebytes * @return * @throws Un
Supportedencodingexception */public static responseentity<byte[]> getresponseentity (String fileName, Byte[] filebytes) throws Unsupportedencodingexception {Http Headers hEaders = new Httpheaders (); Set filename headers.setcontentdispositionformdata ("Attachment", New String (Filename.getbytes ("gb2312")
), "iso-8859-1");
Headers.setcontenttype (Mediatype.application_octet_stream);
return new responseentity<byte[]> (filebytes, headers, httpstatus.ok);
}
}
Export Excel:
/** * Export * @param query * @return * @throws unsupportedencodingexception * * @Reques Tmapping (value = {"/exportpurchaserecord"}) public @ResponseBody responseentity<byte[]> Exportpurchasere Cord (purchaserecordquery query) throws unsupportedencodingexception {list<purchaserecord> List = This.bo.ex Portpurchaserecord (query)/Check database linkedhashmap<string, string> columnmap = new linkedhashmap<string, Stri
Ng> ();
Columnmap.put ("Order Number", "Purchaseno");
Columnmap.put ("Payment number", "orderNo");
Columnmap.put ("member account", "name");
Columnmap.put ("Member Mobile number", "mobile");
Columnmap.put ("The next single Time", "addtime");
Columnmap.put ("Order Status", "Statusstr");
Columnmap.put ("Payment Amount", "totalprice");
Columnmap.put ("Payment Time", "paytime");
Columnmap.put ("Order Product description", "ProductName");
byte[] ExportData = exportutil.exportstr (Columnmap, list); Return fileutil.getresponseentity ("GamelIfe-mall-order.csv ", ExportData = = null?
New Byte[0]: ExportData);
}
exportutil.java
Import Org.apache.commons.lang.StringUtils;
Import Org.apache.log4j.Logger;
Import Java.io.ByteArrayOutputStream;
Import Java.io.DataOutputStream;
Import java.io.IOException;
Import Java.lang.reflect.Method;
Import java.util.*;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;
/** * Export Auxiliary class * * * public class Exportutil {private static Logger log = Logger.getlogger (Exportutil.class); /** * Export method entry, processing result set into byte[] data, incoming parameter labelvaluemap, put into [header: Pojo corresponding field] * * @param labelvaluemap * @param datal IST * @return */public static byte[] Exportstr (linkedhashmap<string, string> labelvaluemap, list<?
> dataList) {if Collectionutil.isempty (dataList) | | | labelvaluemap = = NULL | | labelvaluemap.size () = 0) {
return null;
} linkedhashmap<string, method> methodmap = new linkedhashmap<string, method> ();
Class<?> clazz = datalist.get (0). GetClass (); For (map.entry<string, STring> Entry:labelValueMap.entrySet ()) {String methodname = Entry.getvalue ();
if (Stringutils.isblank (methodname)) {continue; else if (!methodname.startswith ("get")) {methodname = ' get ' + methodname.substring (0, 1). toUpperCase ()
+ methodname.substring (1);
try {method m = Clazz.getmethod (methodname);
Methodmap.put (Entry.getkey (), m);
catch (Exception e) {continue;
} return Exportmethod (Methodmap, dataList);
/** * Import method entrance, generally with the next door that exportdatastr more convenient * * @param map * @param * * @return * * * * public static byte[] Exportmethod (linkedhashmap<string, method> map, list<?> dataList) {if (Collec Tionutil.isempty (dataList) | | Map = = NULL | |
Map.size () = = 0) {return null; } Bytearrayoutputstream OutputStream =Null
DataOutputStream dataoutputstream = null;
try {set<string> keyset = Map.keyset ();
OutputStream = new Bytearrayoutputstream ();
DataOutputStream = new DataOutputStream (outputstream);
String Columnjoin = Stringutils.join (Keyset.iterator (), ",") + "\ n";
Dataoutputstream.write (New byte[]{(Byte) 0xEF, (Byte) 0xBB, (byte) 0xBF});
Dataoutputstream.write (Columnjoin.getbytes ("Utf-8"));
for (Object obj:datalist) {if (obj = = null) {continue;
} stack<string> Stack = new stack<string> ();
For (Method M:map.values ()) {Object value = M.invoke (obj);
if (value = = null) {Stack.push ("");
else {Stack.push (Csvhandlerstr (value.tostring ()));
}
} String Valuejoin = Stringutils.join (Stack.iterator (), ",") + "\ n";
Dataoutputstream.write (Valuejoin.getbytes ("Utf-8"));
return Outputstream.tobytearray ();
catch (Exception e) {log.error ("File Export exception", e);
return null; finally {if (null!= dataoutputstream) {try {dataoutputstream.close ()
;
catch (IOException e) {log.error ("Close OutputStreamWriter error.", e);
} if (null!= outputstream) {try {outputstream.close ();
catch (IOException e) {log.error ("OutputStream close error.", e); /** * CSV special character translation * * @param htmlstr * @return/public s Tatic string Csvhandlerstr (String htmlstr) {string str = GETTEXTFROMHTML (HTMLSTR);
CSV format If there is a comma, the whole is enclosed in double quotes, and if there are double quotes, replace the two double quotes, so that the format will not be a problem with the String tempdescription = str; If there is a comma if (Str.contains (",")) {//If there are double quotes, escape the double quotes first and avoid the escape error if (Str.contains ("\") after double quotes are added to the sides.
{tempdescription = str.replace ("\" "," \ "\");
///In the comma escape tempdescription = "\" "+ Tempdescription +" "";
return tempdescription; /** * textfromhtml * * @param htmlstr * * @return/public static String gettextfromhtm L (String htmlstr) {return Delhtmltag (HTMLSTR). ReplaceAll (" ", ""). ReplaceAll ("\ n", ""). ReplaceAll ("\ r", "
"). ReplaceAll (" T "," "); /** * Delhtmltag * * @param htmlstr * * @return/public static String Delhtmltag (Strin G htmlstr) {//define regular expression pattern p_html = Pattern.compile ("<[^>]+>") for HTML tags, pattern.case_insensiti
VE); Matcher m_html = P_html.matcher (HTMLSTR); Htmlstr = M_html.replaceall (""); Filter HTML tags return htmlstr.trim ();
Return text string}}