package cn.feast.coding.tools;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


public class UploadUtils {
	public static String upload(HttpServletRequest request,MultipartFile file,String picPath) throws IllegalStateException, IOException{
		String path = request.getSession().getServletContext().getRealPath(picPath);
		File f = new File(path);
		if(!f.exists()){
			f.mkdirs();
		}
		if(!file.isEmpty()){
			String saveName = UUID.randomUUID().toString() + file.getOriginalFilename().substring
					(file.getOriginalFilename().lastIndexOf("."));
			file.transferTo(new File(path + "/" + saveName));
			return saveName;
		}
		return null;
	}
	
	public static void deleteFile(String filePath,HttpServletRequest request){
		try {
			File file = new File(request.getSession().getServletContext().getRealPath("/"+filePath));   
			if(file.exists()){
				 file.delete();
			}else{
				 throw new Exception("文件不存在:"+filePath);
			}
		} catch (Exception e) {
			 e.printStackTrace();
		}
	}

	/**
	 * 下载附件
	 * @param fileName 附件名
	 * @param fileDownloadPath 附件路径
	 */
	public static void download(String fileName,String fileDownloadPath,HttpServletResponse response){
		File file = new File(fileDownloadPath);
		download(file,fileName,response);
	}

	/**
	 * 下载附件
	 * @param file 附件
	 * @param fileName 附件名
	 */
	public static void download(File file,String fileName,HttpServletResponse response){
		InputStream input = null;
		try {
			input = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		download(input, fileName, response);
	}

	/**
	 * 下载附件
	 * @param input 附件流
	 * @param fileName 附件名
	 */
	public static void download(InputStream input,String fileName,HttpServletResponse response){
		response.setCharacterEncoding("GBK");
		response.setHeader("Content-Type","application/octet-stream; charset=GBK");//
		response.setHeader("Content-Disposition","attachment; filename=" + StringEncodeUtils.gbkToIso88591(fileName));
		
		OutputStream output = null;
		try {
			output = response.getOutputStream();
			IOUtils.copyLarge(input, output);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(input);
			IOUtils.closeQuietly(output);
		}
	}
}
