...
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;
@Controller
public class UploadController {
static String IMAGE_UPLOAD_DIR_REL_PATH = "uploads";
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file)
throws IOException {
String ROOT_ABS_PATH = request.getSession().getServletContext().getRealPath("");
String UPLOAD_DIR_ABS_PATH = ROOT_ABS_PATH + File.separator + IMAGE_UPLOAD_DIR_REL_PATH;
makeDirectory(UPLOAD_DIR_ABS_PATH);
String fileName = file.getOriginalFilename();
String ext = fileName.substring(fileName.lastIndexOf('.'));
String saveFileName = UUID.randomUUID().toString() + ext;
String saveFileAbsPath = UPLOAD_DIR_ABS_PATH + File.separator + saveFileName;
writeFile(saveFileAbsPath, file.getBytes());
Map<String, Object> map = new HashMap<String, Object>();
// 브라우저에서 접근가능한 경로를 uploadPath에 담아서 넘겨줍니다.
map.put("uploadPath", "uploads/" + saveFileName);
return map;
}
/**
* 파일을 씁니다.
*/
private static void writeFile(String path, byte[] bytes) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(path);
os.write(bytes);
} finally {
if (os != null) os.close();
}
}
/**
* 디렉토리가 없는 경우 디렉토리를 생성합니다.
*/
private static void makeDirectory(String dirPath) {
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdir();
}
}
} |
...