Text file download in Java Spring

// View
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

public class TextFileDownloadView extends AbstractView {
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String text = (String) model.get("text");
        String fileName = (String) model.get("fileName");

        setContentType("text/plain; charset=utf-8");
        response.setContentType(getContentType());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
        response.setHeader("Content-Transfer-Encoding", "binary");

        InputStream in = new ByteArrayInputStream(text.getBytes());
        response.setContentLength(in.available());
        OutputStream out = response.getOutputStream();
        try {
            org.apache.commons.io.IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            in.close();
            out.close();
        }
    }
}
// Bean 등록
<beans:bean id="downloadTextFileView" class="com.jigi.TextFileDownloadView" />
// Controller
    @RequestMapping(value = "/textFileDownload")
    public ModelAndView textFileDownload(@ModelAttribute("myVO") MyVO myVO, HttpServletRequest request, ModelMap model) throws Exception {

    	String text = "";
        try {
            // Do Sothing....
            text = myService.get(myVO);            
        } catch (Exception e) {
            // Do Exception....
	    text = "오류";
        } finally {
            model.addAttribute("text", text);
            model.addAttribute("fileName", "file.txt");
     	    return new ModelAndView("downloadTextFileView");
        }
    }

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다