文件上傳下載接口

import com.mwkj.common.constant.CommonConstant;
import com.mwkj.common.log.LogFactory;
import com.mwkj.common.log.LoggerUtil;
import com.mwkj.common.resp.ResponseMessage;
import com.mwkj.common.resp.ResponseMessageCodeEnum;
import com.mwkj.common.util.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.URLEncoder;

/**
 * 做者:
 * 日期:2018-05-17
 * 功能:文件上傳下載接口
 */
@RestController
@RequestMapping("/api/file")
public class FileController {

	private static final LoggerUtil logger = LogFactory.getLogger(FileController.class);


	/**
	 * 文件上傳
	 *
	 * [@param](https://my.oschina.net/u/2303379) file
	 * [@param](https://my.oschina.net/u/2303379) fileName
	 * [@return](https://my.oschina.net/u/556800)
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public ResponseMessage upload(@RequestParam("file") MultipartFile file, @RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) {
		logger.info("FileController.upload start fileName:" + fileName);

		InputStream in = null;
		OutputStream ot = null;

		//判斷文件是否爲空
		if (file.isEmpty()) {
			logger.info("FileController.upload 上傳文件不能爲空");
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_up_file_empty, null);
		}

		if (StringUtils.isBlank(fileName)) {
			//文件名
			fileName = file.getOriginalFilename();
		}
		if (StringUtils.isBlank(fileName)) {
			logger.info("FileController.upload 上傳文件名不能爲空");
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_up_filename_empty, null);
		}
		if (StringUtils.contains(fileName, "..")) {
			logger.info("FileController.upload 只容許上傳圖片");
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_up_file_image, null);
		}

		if (ValidateUtil.isOverSize(file.getSize() / 1000000, CommonConstant.FILEMAXSIZE)) {
			logger.info("FileController.upload 上傳文件超過" + CommonConstant.FILEMAXSIZE + "M");
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_up_file_max_size, null);
		}

		try {
			in = file.getInputStream();
			if (ValidateUtil.isImage(in) == false) {
				logger.info("FileController.upload 上傳文件不合法");
				return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_up_file_illeage, null);
			}
		} catch (IOException e) {
			if (in != null) {
				try {
					in.close();
				} catch (IOException ex) {
					logger.info("上傳文件關閉流異常" + ex.getMessage());
				}
			}
			logger.info("FileController.upload 上傳文件異常");
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_up_file_error, null);
		}

		//文件目錄不存在則建立
		File outFile = new File(CommonConstant.FILEPATH);
		if (!outFile.exists()) {
			outFile.mkdirs();
		}

		//文件最終的存儲位置
		File dest = new File(CommonConstant.FILEPATH + fileName);

		//判斷目標文件所在的目錄是否存在
		if (!dest.getParentFile().exists()) {
			//若是目標文件所在的目錄不存在,則建立父目錄
			logger.info("FileController.upload 上傳文件所處目錄不存在,建立");
			//建立目錄
			if (!dest.getParentFile().mkdirs()) {
				logger.info("建立上傳文件所處目錄失敗");
				return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_up_file_create_error, null);
			}
		}
		try {
			in = file.getInputStream();
			ot = new FileOutputStream(CommonConstant.FILEPATH + fileName);
			byte[] buffer = new byte[1024];
			int len;
			while ((-1 != (len = in.read(buffer)))) {
				ot.write(buffer, 0, len);
			}
			logger.info("上傳文件成功");
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_up_file_success, StringUtils.replace(request.getRequestURL().toString(), "upload", "download") + "?fileName=" + fileName);
		} catch (IOException e) {
			logger.info("FileController.upload 上傳文件異常");
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_up_file_error, null);
		} finally {
			//關閉各類流
			if (ot != null) {
				try {
					ot.close();
				} catch (IOException e) {
					logger.info("上傳文件關閉流異常" + e.getMessage());
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.info("上傳文件關閉流異常" + e.getMessage());
				}
			}
			logger.info("FileController.upload end fileName:" + fileName);
		}
	}

	/**
	 * 文件下載
	 *
	 * @param fileName
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/download")
	public ResponseMessage downloadFile(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) {
		logger.info("FileController.downloadFile start fileName:" + fileName);
		if (StringUtils.isBlank(fileName)) {
			logger.info("FileController.downloadFile 下載文件名不能爲空");
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_dn_filename_empty, null);
		}
		if (StringUtils.contains(fileName, "..")) {
			logger.info("FileController.downloadFile 下載文件名不合法");
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_dn_file_illeage, null);
		}

		//重置buffer
		response.resetBuffer();
		//設定編碼爲UTF-8
		response.setCharacterEncoding("UTF-8");
		//設置頭部爲下載信息
		response.setHeader("Content-type", "application/force-download;charset=UTF-8");
		try {
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.contains(fileName, "/") ? StringUtils.substringAfter(fileName, "/") : fileName, "UTF-8"));// 設置文件名
		} catch (UnsupportedEncodingException e) {
			logger.info("下載設置文件名異常" + e.getMessage());
		}


		//各類流信息
		FileInputStream fileInputStream = null;
		BufferedInputStream bufferedInputStream = null;
		OutputStream outputStream = null;

		try {
			byte[] buffer = new byte[1024];
			fileInputStream = new FileInputStream(CommonConstant.FILEPATH + fileName);
			bufferedInputStream = new BufferedInputStream(fileInputStream);
			outputStream = response.getOutputStream();
			int i = bufferedInputStream.read(buffer);
			while (i != -1) {
				outputStream.write(buffer, 0, i);
				i = bufferedInputStream.read(buffer);
			}
			logger.info("下載文件成功");
			return ResponseMessage.successResponse();
		} catch (Exception e) {
			logger.info("下載文件異常" + e.getMessage());
			return ResponseMessage.createResponse(ResponseMessageCodeEnum.req_api_dn_file_fail, null);
		} finally {
			//關閉各類流
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					logger.info("下載文件關閉流異常" + e.getMessage());
				}

			}
			if (bufferedInputStream != null) {
				try {
					bufferedInputStream.close();
				} catch (IOException e) {
					logger.info("下載文件關閉流異常" + e.getMessage());
				}
			}
			if (fileInputStream != null) {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					logger.info("上傳文件異常" + e.getMessage());
				}
			}
			logger.info("FileController.downloadFile end fileName:" + fileName);
		}
	}
}
相關文章
相關標籤/搜索