English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

spring mvc를 사용한 파일 업로드 및 다운로드 기능 구현

이 문서는 spring mvc로 파일 업로드 및 다운로드 기능을 구현한 구체적인 코드를 공유합니다. 참고용으로 사용해 주세요. 구체적인 내용은 다음과 같습니다

파일 업로드

pom.xml에 spring mvc와 commons를 포함시키세요-fileupload 관련 jar

  <!-- spring mvc -->
  dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.3.13.RELEASE</version>
  </dependency>
  <!-- 파일 업로드 및 다운로드 -->
  dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
  </dependency>

springmvc.xml에 파일 업로드 관련 설정 추가

 <bean id="multipartResolver" 
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
  <!-- 업로드 파일 크기 최대 제한, 단위는 바이트입니다(10MB) -->
  <property name="maxUploadSize"> 
   <value>10485760</value> 
  </property> 
  <!-- 요청编码 형식은 jSP의 pageEncoding 속성과 일치해야 하며, 양식 내용을 올바르게 읽기 위해 필요합니다. 기본적으로 ISO입니다-8859-1 -->
  <property name="defaultEncoding">
   <value>UTF-8</value>
  </property>
 </bean>

jsp 파일에 form 양식 추가

<form action="upload" enctype="multipart/form-data" method="post">
 <table>
  <tr>
   <td>파일 설명:</td>
   <td><input type="text" name="description"></td>
  </tr>
  <tr>
   <td>파일 선택하십시오:</td>
   <td><input type="file" name="file"></td>
  </tr>
  <tr>
   <td><input type="submit" value="업로드"></td>
  </tr>
 </table>
</form>

파일 업로드 메서드 추가

//업로드 파일은 자동으로 MultipartFile에 바인딩됩니다
@RequestMapping(value="/upload", method = RequestMethod.POST)
public String upload(HttpServletRequest request,
  @RequestParam("description") String description,
  @RequestParam("file") MultipartFile file) throws Exception {
 //파일이 비어 있지 않으면, 업로드 경로를 쓰습니다
 if(!file.isEmpty()) {
  //업로드 파일 경로
  String path = request.getServletContext().getRealPath("/file/");
  //업로드 파일 이름
  String filename = file.getOriginalFilename();
  File filepath = new File(path,filename);
  //경로가 존재하는지 확인합니다. 존재하지 않으면 생성합니다
  if (!filepath.getParentFile().exists()) {
   filepath.getParentFile().mkdirs();
  }
  //업로드 파일을 목표 파일에 저장합니다
  file.transferTo(new File(path + File.separator + filename));
  return "success";
 } else {
  return "error";
 }
}

이것이 본 문서의 모든 내용입니다. 여러분의 학습에 도움이 되길 바라며, 모두들呐喊 튜토리얼을 많이 지지해 주시길 바랍니다.

언급: 본 문서는 인터넷에서 가져왔으며, 저작권자는 모두 소유합니다. 내용은 인터넷 사용자가 자발적으로 기여하고 업로드한 것이며, 사이트는 소유권을 가지지 않으며, 인공編集을 하지 않았으며, 관련 법적 책임도 부담하지 않습니다. 저작권 위반 내용을 발견하시면, notice#w로 이메일을 보내 주시기 바랍니다.3codebox.com(이메일을 보내는 경우, #을 @으로 변경하십시오. 신고하고 관련 증거를 제공하시면, 사이트는 즉시 위반 내용을 삭제합니다.

추천 항목