1. 程式人生 > >上傳下載檔案、匯出excel

上傳下載檔案、匯出excel

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(FileUploadController.class);

	@Value("${shop.back.uploadUrl}")
	private String uploadUrl;

	@Value("${shop.back.uploadDir}")
	private String uploadDir;

	/**
	 * 上次檔案(先到臨時目錄)
	 *
	 * @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("檔案上傳失敗:", e);
		}
		return new ModelAndView("/result.jsp").addObject("json", json.toString());
	}

	/**
	 * 下載檔案
	 *
	 * @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.separator + 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("檔案上傳失敗:", 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 = "/";

    /**
     * 建立目錄
     *
     * @param dirPath
     */
    public static void mkdirs(String dirPath) {
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
    }

    /**
     * 刪除檔案
     *
     * @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));
    }

    /**
     * 刪除檔案和目錄
     *
     * @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();
    }

    /**
     * 獲取一個隨機的檔名
     *
     * @param realFilename
     * @return
     */
    public static String getRandomFileName(String realFilename) {
        String newFileName = Calendar.getInstance().getTimeInMillis() + RandomUtil.getNumberCode(4);
        int index = realFilename.lastIndexOf(".");
        if (index >= 0) {
            newFileName += realFilename.substring(index);
        }
        return newFileName;
    }

    /**
     * 獲取一個新檔案物件,存在先刪除
     *
     * @param filePath
     * @return
     */
    public static File getNewFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    /**
     * 建立一個檔案,如果檔案存在就先刪除再建立一個新的
     *
     * @param filePath 檔案完整路徑
     * @return 返回新建立的檔案
     */
    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;
    }

    /**
     * 生成帶版本號的檔名
     *
     * @param fileName
     * @param
     * @return
     */
    public static String getFileVersionName(String fileName, int version) {
        int index = fileName.lastIndexOf(".");
        return fileName.substring(0, index) + version + fileName.substring(index);
    }

    /**
     * 檢查檔案路徑是否存在
     *
     * @param filePath
     * @return
     */
    public static boolean checkFileExist(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * 返回檔案的副檔名
     *
     * @param fileName
     * @return
     */
    public static String getExtension(String fileName) {
        return getExtension(fileName, "");
    }

    public static String getExtension(String fileName, String ext) {
        if (fileName != null && fileName.length() > 0) {
            int i = fileName.lastIndexOf(".");
            if (i > -1 && i < (fileName.length() - 1)) {
                return fileName.substring(i + 1);
            }
        }
        return ext;
    }

    /**
     * 根據檔案讀取txt內容
     *
     * @param pathname
     * @return
     */
    public static List getListByTxt(String pathname) {
        List<String> list = new ArrayList<String>();
        File filename = new File(pathname); // 要讀取以上路徑的input。txt檔案
        InputStreamReader reader = null; // 建立一個輸入流物件reader
        try {
            reader = new InputStreamReader(
                    new FileInputStream(filename));

            BufferedReader br = new BufferedReader(reader); // 建立一個物件,它把檔案內容轉成計算機能讀懂的語言
            String line = "";
            line = br.readLine();
            if (StringUtil.isNotNullStr(line)) {
                list.add(line);
            }
            while (line != null) {
                line = br.readLine(); // 一次讀入一行資料
                if (StringUtil.isNotNullStr(line)) {
                    list.add(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * getResponseEntity
     *
     * @param fileName
     * @param fileBytes
     * @return
     * @throws UnsupportedEncodingException
     */
    public static ResponseEntity<byte[]> getResponseEntity(String fileName,
                                                           byte[] fileBytes) throws UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        // 設定檔名
        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);
    }

}

匯出excel:

   /**
     * 匯出
     *
     * @param query
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = {"/exportPurchaseRecord"})
    public
    @ResponseBody
    ResponseEntity<byte[]> exportPurchaseRecord(PurchaseRecordQuery query) throws UnsupportedEncodingException {
        List<PurchaseRecord> list = this.bo.exportPurchaseRecord(query);//查資料庫
        LinkedHashMap<String, String> columnMap = new LinkedHashMap<String, String>();
        columnMap.put("訂單號", "purchaseNo");
        columnMap.put("支付號", "orderNo");
        columnMap.put("會員賬號", "name");
        columnMap.put("會員手機號", "mobile");
        columnMap.put("下單時間", "addTime");
        columnMap.put("訂單狀態", "statusStr");
        columnMap.put("支付金額", "totalPrice");
        columnMap.put("支付時間", "payTime");
        columnMap.put("訂單商品描述", "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;

/**
 * 匯出輔助類
 */
public class ExportUtil {
    private static Logger log = Logger.getLogger(ExportUtil.class);

    /**
     * 匯出方法入口,把結果集處理成byte[]資料,傳入引數labelValueMap,放入[表頭:pojo對應欄位]
     *
     * @param labelValueMap
     * @param dataList
     * @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);
    }

    /**
     * 匯入方法入口,一般用隔壁那個exportDataStr更為簡便
     *
     * @param map
     * @param dataList
     * @return
     */
    public static byte[] exportMethod(LinkedHashMap<String, Method> map, List<?> dataList) {
        if (CollectionUtil.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("檔案匯出異常", 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特殊字元轉譯
     *
     * @param htmlStr
     * @return
     */
    public static String csvHandlerStr(String htmlStr) {
        String str = getTextFromHtml(htmlStr);
        // csv格式如果有逗號,整體用雙引號括起來;如果裡面還有雙引號就替換成兩個雙引號,這樣匯出來的格式就不會有問題了
        String tempDescription = str;
        // 如果有逗號
        if (str.contains(",")) {
            // 如果還有雙引號,先將雙引號轉義,避免兩邊加了雙引號後轉義錯誤
            if (str.contains("\"")) {
                tempDescription = str.replace("\"", "\"\"");
            }
            // 在將逗號轉義
            tempDescription = "\"" + tempDescription + "\"";
        }
        return tempDescription;
    }

    /**
     * TextFromHtml
     *
     * @param htmlStr
     * @return
     */
    public static String getTextFromHtml(String htmlStr) {
        return delHTMLTag(htmlStr).replaceAll(" ", " ").replaceAll("\n", " ").replaceAll("\r", " ")
                .replaceAll("\t", " ");
    }

    /**
     * delHTMLTag
     *
     * @param htmlStr
     * @return
     */
    public static String delHTMLTag(String htmlStr) {
        // 定義HTML標籤的正則表示式
        Pattern p_html = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // 過濾html標籤
        return htmlStr.trim(); // 返回文字字串
    }

}