2020년 5월 12일 화요일

[Spring] Uploading files from a spring

pom.xml

 Enter the libraries required to upload the file into pom.xml.

pom.xml
<!-- Apache Commons FileUpload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

Set Empty Object


root-context.xml
<!-- MultipartResolver 설정 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="maxUploadSize" value="100000000" />
  <property name="maxInMemorySize" value="100000000" />
</bean>
 Injects a MultipartResolver bin that allows you to receive files. With the maxUploadSize property, you can set the maximum size of the file to be uploaded, and you can set the maximum capacity that can be allowed to remain in memory with maxInMemorySize.

Jsp file

 Jsp screen to transfer files to.
example
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="제출"/>
</form>
 The file transfer is sent in post format only and sets the roottype to multipart/form-data. Then enter the input tag to which you want to upload.

When using Spring Secutiry
<form:form action="/upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="제출"/>
</form:form>
If you are using spring security after request url, "?You must paste ${_csrf.parameterName}=${_csrf.token}" before you can request it with that url.

Controller

Method of controller file that is executed upon request from form tag.

example
@RequestMapping(value = "/upload" , method = RequestMethod.POST)
public String upload(MultipartHttpServletRequest mtf) throws Exception {
 // 파일 태그
 String fileTag = "file";
     // 업로드 파일이 저장될 경로
 String filePath = "C:\\temp\\";
 // 파일 이름 
 MultipartFile file = mtf.getFile(fileTag);
 String fileName = file.getOriginalFilename();
 // 파일 전송
 try {
     file.transferTo(new File(filePath + fileName));
 } catch(Exception e) {
     System.out.println("업로드 오류");
 }
           ...
}
 The file information sent to the form tag will be received in the form of MultipartHttpServletRequest and will be included as a method parameter. Then create a variable called fileTag to enter a value for the name property entered in the form tag. In the filePath variable, enter the path where the uploaded file will be stored. You then create a MultipartFile object to save the transferred file information and save the file name in the fileName variable by the getOrganalFilename method. Finally, the upload completes when you pass the file object with the full path of the upload file entered into the transforTo method as a parameter.

댓글 없음:

댓글 쓰기