ファイルのアップロード、ダウンロード


ファイルのアップロード
servlet-context.xmlにコンテンツを追加
	<beans:bean id="multipartResolver"     
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<beans:property name="defaultEncoding" value="UTF-8" />
		<beans:property name="maxUploadSize" value="10485760" />
		<beans:property name="maxUploadSizePerFile" value="2097152"/>
		<beans:property name="maxInMemorySize" value="10485756"/>
	</beans:bean>
pom.xmlコンテンツの追加
<!-- commons-fileupload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.1</version> 
		</dependency>
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.5</version>
		</dependency>
-FileController.java
import java.io.File;
import java.util.ArrayList;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import park.md.filesetting.Path;
import park.md.service.FileUploadService;

@AllArgsConstructor
@Log4j
@Controller
@RequestMapping("file")
public class FileController {
	private FileUploadService service; // auto injection

	@GetMapping("form.do")
	public String formFu() { //form File Upload
		return "file/form";
	}
	@GetMapping("form_mt.do")
	public String formFu_mt() { //form File Upload
		return "file/form_mt";
	}
	@PostMapping("upload.do")
	public String upload(@RequestParam String name, @RequestParam MultipartFile file) {
		log.info("#name: " + name + ", file: " + file);
		
		String ofname = file.getOriginalFilename();
		if(ofname != null) ofname = ofname.trim();
		if(ofname.length() != 0) {
			String url = service.saveStore(file);
			log.info(url);
		}
		
		return "redirect:list.do";
	}
	@GetMapping("list.do")
	public ModelAndView fileList() {
		File fStore = new File(Path.FILE_STORE);
		if(!fStore.exists()) fStore.mkdir();
		File files[] = fStore.listFiles();
		
		return new ModelAndView("file/list", "files", files);
	}
	@GetMapping("del.do")
	public String del(@RequestParam String fname) {
		File file = new File(Path.FILE_STORE, fname);
		if(file.exists()) file.delete();
		log.info(fname);
		
		return "redirect:list.do";
	}
	@PostMapping("upload_mt.do")
	public String uploadMt(@RequestParam ArrayList<MultipartFile> files) {
		//multi file upload logic
		for(MultipartFile file:files) {
			String ofname = file.getOriginalFilename();
			if(ofname != null) ofname = ofname.trim();
			if(ofname.length()!=0) {
				String url = service.saveStore(file);
			}
		}
		
		return "redirect:list.do";
	}
}
-FileUploadService.java
import java.util.ArrayList;

import org.springframework.web.multipart.MultipartFile;

public interface FileUploadService {
	String saveStore(MultipartFile file);
	boolean writeFile(MultipartFile file, String saveFileNmae);
}
-FileUploadServiceImple.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.log4j.Log4j;
import park.md.filesetting.*;

@Log4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

	@Override
	public String saveStore(MultipartFile file) {
		String ofname = file.getOriginalFilename();
		int idx = ofname.lastIndexOf(".");
		String ofheader = ofname.substring(0, idx);
		String ext = ofname.substring(idx);
		long ms = System.currentTimeMillis();
		StringBuilder sb = new StringBuilder();
		sb.append(ofheader);
		sb.append("_");
		sb.append(ms);
		sb.append(ext);
		String saveFileName = sb.toString();
		
		long fsize = file.getSize();
		log.info("#ofname: " + ofname + ", saveFileName: " + saveFileName + ", fsize: "+fsize);
		
		boolean flag = writeFile(file, saveFileName);
		if(flag) {
			log.info("#업로드 성공");
		}else {
			log.info("#업로드 실패");
		}
		return Path.FILE_STORE + saveFileName;
	}
	
	@Override
	public boolean writeFile(MultipartFile file, String saveFileName) {
		File rDir = new File(Path.FILE_STORE);
		if(!rDir.exists()) rDir.mkdirs();
		
		FileOutputStream fos = null;
		try {
			byte data[] = file.getBytes();
			fos = new FileOutputStream(Path.FILE_STORE+saveFileName);
			fos.write(data);
			fos.flush();
			
			return true;
		}catch(IOException ie) {
			return false;
		}finally {
			try {
				if(fos != null) fos.close();
			}catch(IOException ie) {}
		}
	}
}
Path.java

public class Path {
	public static final String FILE_STORE = "C:/UploadDirectory/";
}
ファイルのダウンロード
servlet-context.xml
<beans:bean id="fileDownloadView" class="(package).FileDownloadView" />
<beans:bean id="fileViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver">
	<beans:property name="order" value="0" />
</beans:bean>
FileDownloadView.Javaファイルの作成
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

import lombok.extern.log4j.Log4j;

@Log4j
public class FileDownloadView extends AbstractView {
	public FileDownloadView() {
		setContentType("application/download;charset=utf-8");
	}
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		File file = (File)model.get("downloadFile");
		
		response.setContentType(getContentType());
		response.setContentLength((int)file.length());
		String value = "attachment; filename="+ java.net.URLEncoder.encode(file.getName(), "utf-8") +";";
		response.setHeader("Content-Disposition", value);
		response.setHeader("Content-Transfer-Encoding", "binary");
		
		OutputStream os = response.getOutputStream();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			FileCopyUtils.copy(fis, os); // 반복문을 통하지 않고 한번에 다운로드 강려크!!
			
			os.flush();
		}catch(IOException ie) {
			log.info("FilewDownloadView ie : "+ie);
		}finally {
			try {
				if(fis != null) fis.close();
				if(os != null) os.close();
			}catch(IOException ie) {}
		}
	}
}
FileController.Javaコンテンツの追加
@GetMapping("download.do")
	public ModelAndView download(@RequestParam String fname) {
		File file = new File(Path.FILE_STORE, fname);
		if(file.exists()) {
			return new ModelAndView("fileDownloadView", "downloadFile", file);
		}else {
			return new ModelAndView("redirect:list.do");
		}
	}