package com.uas.search.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/upload")
public class UploadController {

	private static final String UPLOAD_DIR = System.getProperty("java.io.tmpdir");

	private static Logger logger = LoggerFactory.getLogger(UploadController.class);

	@RequestMapping
	@ResponseBody
	public String upload(MultipartFile file, HttpServletRequest request) {
		String message = "";
		if (file == null || file.isEmpty()) {
			message = "文件为空，无法进行上传！";
			logger.error(message);
			return message;
		}

		String fileName = file.getOriginalFilename();
		String targetFilePath = (UPLOAD_DIR.endsWith(File.separator) ? UPLOAD_DIR : UPLOAD_DIR + "/") + fileName;
		File targetFile = new File(targetFilePath);
		if (!targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}
		try {
			file.transferTo(targetFile);
			message = "成功上传文件至 ：" + targetFile.getCanonicalPath();
			logger.info(message);
			return message;
		} catch (IllegalStateException | IOException e) {
			logger.error("", e);
		}

		message = "上传文件失败： " + fileName;
		logger.error(message);
		return message;
	}
}
