Java tutorial
/* * * Copyright 2018 FJN Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author Date Issue * fs1194361820@163.com 2015-01-01 Initial Version * */ package com.fjn.helper.common.io.file.common; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.activation.MimetypesFileTypeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.servlet.ServletRequestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings("rawtypes") public class FileUpAndDownloadUtil { private static Logger log = LoggerFactory.getLogger(FileUpAndDownloadUtil.class); private static MimetypesFileTypeMap mimetypesMap = null; static { try { mimetypesMap = new MimetypesFileTypeMap("my.mime.types"); } catch (IOException e) { e.printStackTrace(); } } /** * ??????? * @param klass ???klass?Class * @param filepath ? * @param sizeThreshold ?? * @param isFileNameBaseTime ???? * @return bean */ public static <T> Object upload(HttpServletRequest request, Class<T> klass, String filepath, int sizeThreshold, boolean isFileNameBaseTime) throws Exception { FileItemFactory fileItemFactory = null; if (sizeThreshold > 0) { File repository = new File(filepath); fileItemFactory = new DiskFileItemFactory(sizeThreshold, repository); } else { fileItemFactory = new DiskFileItemFactory(); } ServletFileUpload upload = new ServletFileUpload(fileItemFactory); ServletRequestContext requestContext = new ServletRequestContext(request); T bean = null; if (klass != null) { bean = klass.newInstance(); } // if (ServletFileUpload.isMultipartContent(requestContext)) { File parentDir = new File(filepath); List<FileItem> fileItemList = upload.parseRequest(requestContext); for (int i = 0; i < fileItemList.size(); i++) { FileItem item = fileItemList.get(i); // ?? if (item.isFormField()) { String paramName = item.getFieldName(); String paramValue = item.getString("UTF-8"); log.info("?" + paramName + "=" + paramValue); request.setAttribute(paramName, paramValue); // ?bean if (klass != null) { Field field = null; try { field = klass.getDeclaredField(paramName); if (field != null) { field.setAccessible(true); Class type = field.getType(); if (type == Integer.TYPE) { field.setInt(bean, Integer.valueOf(paramValue)); } else if (type == Double.TYPE) { field.setDouble(bean, Double.valueOf(paramValue)); } else if (type == Float.TYPE) { field.setFloat(bean, Float.valueOf(paramValue)); } else if (type == Boolean.TYPE) { field.setBoolean(bean, Boolean.valueOf(paramValue)); } else if (type == Character.TYPE) { field.setChar(bean, paramValue.charAt(0)); } else if (type == Long.TYPE) { field.setLong(bean, Long.valueOf(paramValue)); } else if (type == Short.TYPE) { field.setShort(bean, Short.valueOf(paramValue)); } else { field.set(bean, paramValue); } } } catch (NoSuchFieldException e) { log.info("" + klass.getName() + "?" + paramName); } } } // else { // <input type='file' name='xxx'> xxx String paramName = item.getFieldName(); log.info("?" + item.getSize()); if (sizeThreshold > 0) { if (item.getSize() > sizeThreshold) continue; } String clientFileName = item.getName(); int index = -1; // ?IE? if ((index = clientFileName.lastIndexOf("\\")) != -1) { clientFileName = clientFileName.substring(index + 1); } if (clientFileName == null || "".equals(clientFileName)) continue; String filename = null; log.info("" + paramName + "\t??" + clientFileName); if (isFileNameBaseTime) { filename = buildFileName(clientFileName); } else filename = clientFileName; request.setAttribute(paramName, filename); // ?bean if (klass != null) { Field field = null; try { field = klass.getDeclaredField(paramName); if (field != null) { field.setAccessible(true); field.set(bean, filename); } } catch (NoSuchFieldException e) { log.info("" + klass.getName() + "? " + paramName); continue; } } if (!parentDir.exists()) { parentDir.mkdirs(); } File newfile = new File(parentDir, filename); item.write(newfile); String serverPath = newfile.getPath(); log.info("?" + serverPath); } } } return bean; } public static void downloadToBrowser(String filename, String realpath, HttpServletRequest request, HttpServletResponse response) { // ?MIME TYPE? //try { // mimetypesMap=new MimetypesFileTypeMap(request.getSession().getServletContext().getRealPath("WEB-INF/my.mime.types")); mimetypesMap = new MimetypesFileTypeMap(); //} catch (IOException e1) { // e1.printStackTrace(); //} // response.setCharacterEncoding("UTF-8"); response.setContentType(mimetypesMap.getContentType(filename)); response.addHeader("Content-Disposition", "attachment;filename=" + toUTF8(filename)); FileInputStream in = null; OutputStream out = null; try { /* ???? BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream(new File(realpath)))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter( response.getOutputStream())); int length = -1; char[] chs = new char[1024]; while ((length = in.read(chs)) != -1) { out.write(chs, 0, length); } */ in = new FileInputStream(new File(realpath)); out = response.getOutputStream(); int length = -1; byte[] bs = new byte[1024]; while ((length = in.read(bs)) != -1) { out.write(bs, 0, length); } out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (Exception ex) { } } } // ?? private static String toUTF8(String str) { return FileUtil.getFileNameForDownload(str); } private static String getTime() { return new SimpleDateFormat("_yyyyMMdd_HHmmss").format(new Date()); } // ????__.?? // private static String buildFileName(String filename) { int index = filename.lastIndexOf("."); if (index == -1) { index = filename.length(); } StringBuilder builder = new StringBuilder(filename); return builder.insert(index, getTime()).toString(); } public static void testBuildFileName(String[] args) { // ???zhangsan_20130721_112825.txt System.out.println(buildFileName("zhangsan.txt")); } public static void main(String[] args) { String contetntype = null; contetntype = mimetypesMap.getContentType(new File("com/caxk/workreport/??.doc")); log.info(contetntype); contetntype = mimetypesMap.getContentType(new File("Hel.xls")); log.info(contetntype); } }