< form action="fileupload" method="post" enctype="multipart/form-data“ accept-charset="UTF-8" > < input type="file" name="uploadfile" /> < input type="submit" value="업로드"> < /form>
1) pom.xml 의존성 설정
< dependency > < groupId >commons-fileupload< /groupId > < artifactId >commons-fileupload< /artifactId > < version >버전< /version > < /dependency >
2) 빈 객체 등록
< bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver“/> < property name="maxUploadSize" value="5242880" /> <!-- 5MB --> < property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
@RequestMapping(value = "/fileupload", method = RequestMethod.POST) public void upload(MultipartFile uploadfile, HttpServletRequest req) { String uploadPath = req.getRealPath("upload"); // 서버 실제 경로 String saveName = uploadfile.getOriginalFilename(); File saveFile = new File(uploadPath, saveName); // 저장할 폴더 이름, 저장할 파일 이름 try { uploadfile.transferTo(saveFile); } catch (IOException e) { e.printStackTrace(); } }
@RequestMapping(value = "/fileupload") public String requestupload2(MultipartHttpServletRequest multiPart, HttpServletRequest req) { List<MultipartFile> fileList = multiPart.getFiles("uploadfile”); String name = multiPart.getParameter(input name); String uploadPath = req.getRealPath(“upload”); for (MultipartFile mf : fileList) { String originFileName = mf.getOriginalFilename(); // 원본 파일 명 String safeFile = uploadPath + System.currentTimeMillis() + originFileName; mf.tarnsferTo(new File(safeFile)); } return "경로"; }
String fileName = request.getParameter("filename"); String sFilePath = request.getRealPath("upload")+"/" + fileName; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sFilePath)); BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); byte b[] = new byte [4096]; int numRead; while((numRead = bis.read(b, 0, b.length)) != -1) { bos.write(b, 0, numRead); } bos.flush(); bos.close(); bis.close();