springboot 업로드 파일 (서버에 저장하고 데이터베이스 테이블에 URL 저장)

public R upLoadAccessory(@RequestParam("file")MultipartFile file){
		
		Map map = new HashMap<>();
		
		if (file.isEmpty()) {
			return R.ok(map);
			
		}else {
			
			// 
			DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 
			Calendar calendar = Calendar.getInstance(); 
			String dateName = df.format(calendar.getTime())+file.getOriginalFilename();
			
			System.out.println(dateName);
			// 
			WebApplicationContext webApplicationContext = (WebApplicationContext)SpringContextUtils.applicationContext; 
			ServletContext servletContext = webApplicationContext.getServletContext();
			String realPath = servletContext.getRealPath("/");
			String filePath = realPath + "WEB-INF"+File.separator + "classes" + File.separator +"static" + File.separator + "resource" + File.separator+dateName;
			System.out.println(" :"+filePath);
			
			File newFile = new File(filePath);
			
			//MultipartFile 
			try {
				
				// 
				file.transferTo(newFile);
				
				// 
				String projectPath = servletContext.getContextPath();
				HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
				String contextpath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+projectPath;
				String url = contextpath + "/resource/"+dateName;
				System.out.println(" :"+url);
				// URL 
				....
				
				
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
			
		}
		return R.ok(map);
	}

2018.5.16 업데이트: 도구 클래스 추가
@Component
public class SpringContextUtils implements ApplicationContextAware {
	public static ApplicationContext applicationContext; 

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}

	public static Object getBean(String name) {
		return applicationContext.getBean(name);
	}

	public static  T getBean(String name, Class requiredType) {
		return applicationContext.getBean(name, requiredType);
	}

	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}

	public static boolean isSingleton(String name) {
		return applicationContext.isSingleton(name);
	}

	public static Class extends Object> getType(String name) {
		return applicationContext.getType(name);
	}

}

2019.8.6 업데이트 - HttpContextutils 도구 클래스
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class HttpContextUtils {

	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
}

좋은 웹페이지 즐겨찾기