Uploader.java 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package ueditor;
  2. import java.io.*;
  3. import java.text.SimpleDateFormat;
  4. import java.util.*;
  5. import org.apache.commons.fileupload.*;
  6. import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;
  7. import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
  8. import org.apache.commons.fileupload.util.*;
  9. import org.apache.commons.fileupload.servlet.*;
  10. import org.apache.commons.fileupload.FileItemIterator;
  11. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  12. import sun.misc.BASE64Decoder;
  13. import javax.servlet.http.HttpServletRequest;
  14. /**
  15. * UEditor文件上传辅助类
  16. *
  17. */
  18. public class Uploader {
  19. // 输出文件地址
  20. private String url = "";
  21. // 上传文件名
  22. private String fileName = "";
  23. // 状态
  24. private String state = "";
  25. // 文件类型
  26. private String type = "";
  27. // 原始文件名
  28. private String originalName = "";
  29. // 文件大小
  30. private String size = "";
  31. private HttpServletRequest request = null;
  32. private String title = "";
  33. // 保存路径
  34. private String savePath = "upload";
  35. // 文件允许格式
  36. private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
  37. // 文件大小限制,单位KB
  38. private int maxSize = 10000;
  39. private HashMap<String, String> errorInfo = new HashMap<String, String>();
  40. public Uploader(HttpServletRequest request) {
  41. this.request = request;
  42. HashMap<String, String> tmp = this.errorInfo;
  43. tmp.put("SUCCESS", "SUCCESS"); //默认成功
  44. tmp.put("NOFILE", "未包含文件上传域");
  45. tmp.put("TYPE", "不允许的文件格式");
  46. tmp.put("SIZE", "文件大小超出限制");
  47. tmp.put("ENTYPE", "请求类型ENTYPE错误");
  48. tmp.put("REQUEST", "上传请求异常");
  49. tmp.put("IO", "IO异常");
  50. tmp.put("DIR", "目录创建失败");
  51. tmp.put("UNKNOWN", "未知错误");
  52. }
  53. public void upload() throws Exception {
  54. boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
  55. if (!isMultipart) {
  56. this.state = this.errorInfo.get("NOFILE");
  57. return;
  58. }
  59. DiskFileItemFactory dff = new DiskFileItemFactory();
  60. String savePath = this.getFolder(this.savePath);
  61. dff.setRepository(new File(savePath));
  62. try {
  63. ServletFileUpload sfu = new ServletFileUpload(dff);
  64. sfu.setSizeMax(this.maxSize * 1024);
  65. sfu.setHeaderEncoding("utf-8");
  66. FileItemIterator fii = sfu.getItemIterator(this.request);
  67. while (fii.hasNext()) {
  68. FileItemStream fis = fii.next();
  69. if (!fis.isFormField()) {
  70. this.originalName = fis.getName().substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
  71. if (!this.checkFileType(this.originalName)) {
  72. this.state = this.errorInfo.get("TYPE");
  73. continue;
  74. }
  75. this.fileName = this.getName(this.originalName);
  76. this.type = this.getFileExt(this.fileName);
  77. this.url = savePath + "/" + this.fileName;
  78. BufferedInputStream in = new BufferedInputStream(fis.openStream());
  79. FileOutputStream out = new FileOutputStream(new File(this.getPhysicalPath(this.url)));
  80. BufferedOutputStream output = new BufferedOutputStream(out);
  81. Streams.copy(in, output, true);
  82. this.state=this.errorInfo.get("SUCCESS");
  83. //UE中只会处理单张上传,完成后即退出
  84. break;
  85. } else {
  86. String fname = fis.getFieldName();
  87. //只处理title,其余表单请自行处理
  88. if(!fname.equals("pictitle")){
  89. continue;
  90. }
  91. BufferedInputStream in = new BufferedInputStream(fis.openStream());
  92. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  93. StringBuffer result = new StringBuffer();
  94. while (reader.ready()) {
  95. result.append((char)reader.read());
  96. }
  97. this.title = new String(result.toString().getBytes(),"utf-8");
  98. reader.close();
  99. }
  100. }
  101. } catch (SizeLimitExceededException e) {
  102. this.state = this.errorInfo.get("SIZE");
  103. } catch (InvalidContentTypeException e) {
  104. this.state = this.errorInfo.get("ENTYPE");
  105. } catch (FileUploadException e) {
  106. this.state = this.errorInfo.get("REQUEST");
  107. } catch (Exception e) {
  108. this.state = this.errorInfo.get("UNKNOWN");
  109. }
  110. }
  111. /**
  112. * 接受并保存以base64格式上传的文件
  113. * @param fieldName
  114. */
  115. public void uploadBase64(String fieldName){
  116. String savePath = this.getFolder(this.savePath);
  117. String base64Data = this.request.getParameter(fieldName);
  118. this.fileName = this.getName("test.png");
  119. this.url = savePath + "/" + this.fileName;
  120. BASE64Decoder decoder = new BASE64Decoder();
  121. try {
  122. File outFile = new File(this.getPhysicalPath(this.url));
  123. OutputStream ro = new FileOutputStream(outFile);
  124. byte[] b = decoder.decodeBuffer(base64Data);
  125. for (int i = 0; i < b.length; ++i) {
  126. if (b[i] < 0) {
  127. b[i] += 256;
  128. }
  129. }
  130. ro.write(b);
  131. ro.flush();
  132. ro.close();
  133. this.state=this.errorInfo.get("SUCCESS");
  134. } catch (Exception e) {
  135. this.state = this.errorInfo.get("IO");
  136. }
  137. }
  138. /**
  139. * 文件类型判断
  140. *
  141. * @param fileName
  142. * @return
  143. */
  144. private boolean checkFileType(String fileName) {
  145. Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
  146. while (type.hasNext()) {
  147. String ext = type.next();
  148. if (fileName.toLowerCase().endsWith(ext)) {
  149. return true;
  150. }
  151. }
  152. return false;
  153. }
  154. /**
  155. * 获取文件扩展名
  156. *
  157. * @return string
  158. */
  159. private String getFileExt(String fileName) {
  160. return fileName.substring(fileName.lastIndexOf("."));
  161. }
  162. /**
  163. * 依据原始文件名生成新文件名
  164. * @return
  165. */
  166. private String getName(String fileName) {
  167. Random random = new Random();
  168. return this.fileName = "" + random.nextInt(10000)
  169. + System.currentTimeMillis() + this.getFileExt(fileName);
  170. }
  171. /**
  172. * 根据字符串创建本地目录 并按照日期建立子目录返回
  173. * @param path
  174. * @return
  175. */
  176. private String getFolder(String path) {
  177. SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
  178. path += "/" + formater.format(new Date());
  179. File dir = new File(this.getPhysicalPath(path));
  180. if (!dir.exists()) {
  181. try {
  182. dir.mkdirs();
  183. } catch (Exception e) {
  184. this.state = this.errorInfo.get("DIR");
  185. return "";
  186. }
  187. }
  188. return path;
  189. }
  190. /**
  191. * 根据传入的虚拟路径获取物理路径
  192. *
  193. * @param path
  194. * @return
  195. */
  196. private String getPhysicalPath(String path) {
  197. String servletPath = this.request.getServletPath();
  198. String realPath = this.request.getSession().getServletContext()
  199. .getRealPath(servletPath);
  200. return new File(realPath).getParent() +"/" +path;
  201. }
  202. public void setSavePath(String savePath) {
  203. this.savePath = savePath;
  204. }
  205. public void setAllowFiles(String[] allowFiles) {
  206. this.allowFiles = allowFiles;
  207. }
  208. public void setMaxSize(int size) {
  209. this.maxSize = size;
  210. }
  211. public String getSize() {
  212. return this.size;
  213. }
  214. public String getUrl() {
  215. return this.url;
  216. }
  217. public String getFileName() {
  218. return this.fileName;
  219. }
  220. public String getState() {
  221. return this.state;
  222. }
  223. public String getTitle() {
  224. return this.title;
  225. }
  226. public String getType() {
  227. return this.type;
  228. }
  229. public String getOriginalName() {
  230. return this.originalName;
  231. }
  232. }