package com.qmth.jkserver.controller.api;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qmth.jkserver.constant.SystemConstant;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.qmth.jkserver.core.exception.ApiException;
import com.qmth.jkserver.core.upload.FileUploader;
import com.qmth.jkserver.model.Attachment;

/**
 * 
 * 通用文件上传组件
 * 
 * @author tianjun
 *
 */
@RestController
@RequestMapping("/api/jkdevice/common")
public class CommonController {

	@ResponseBody
	@RequestMapping("/upload")
	public Object upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		multipartResolver.setDefaultEncoding(SystemConstant.CHARSET_NAME);
		if (multipartResolver.isMultipart(request)) {
			FileUploader fileUploader = new FileUploader(request);
			List<Attachment> attachments = fileUploader.execute();
			if(attachments.size() > 0){
				Attachment attachment = attachments.get(0);
				return attachment;
			}
			else{
				throw ApiException.FILE_UPLOAD_ERROR;
			}
		}
		else{
			throw ApiException.NOT_FILE_UPLOAD_REQUEST;
		}
	}


	/**
	 * 获取文件的后缀
	 */
	protected String getExtension(String fileName) {
		int k = fileName.lastIndexOf(".");
		String ext = "";
		if (k > 0) {
			ext = fileName.substring(k + 1, fileName.length());
		}
		return ext;
	}

}
