2018年11月29日木曜日

File upload



<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
    <form action="/sample/upload" method="post" enctype="multipart/form-data">

        <p>
        <select name="example1">
        <option value="サンプル1">選択肢のサンプル1</option>
        <option value="サンプル2">選択肢のサンプル2</option>
        <option value="サンプル3">選択肢のサンプル3</option>
        <option value="サンプル4">選択肢のサンプル4</option>
        <option value="サンプル5">選択肢のサンプル5</option>
        </select>
        </p>

        <input type="file" name="upload_file" /><br />
        <button type="submit">upload</button>
    </form>
</body>
</html>


package com.example.demo.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.nio.charset.Charset;
import java.util.List;

import javax.validation.Constraint;
import javax.validation.Payload;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.domain.Fruit;
import com.example.demo.mapper.FruitMapper;

@Controller
public class IndexController {

    @Autowired
    FruitMapper fruitMapper;

    @RequestMapping(value="/i2/", method=RequestMethod.GET)
    public String index(Model model) {
        List<Fruit> list = fruitMapper.selectAll();
        model.addAttribute("fruits", list);
        return "index2";
    }

//    @RequestMapping(value = "/post", method = RequestMethod.POST)
//    public ModelAndView post(
//        HttpServletResponse response, @RequestParam("file") MultipartFile file){
//
//        try {
//            InputStream inputStream = null;
//            InputStreamReader inputStreamReader = null;
//            BufferedReader bufferReader = null;
//
//            inputStream = file.getInputStream();
//            inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
//            bufferReader = new BufferedReader(inputStreamReader);
//
//            String line;
//            while ((line = bufferReader.readLine()) != null) {
//
//                byte[] b = line.getBytes();
//                line = new String(b, "UTF-8");
//                String[] columns = line.split(",",-1);
//
//                for (int i = 0; i < columns.length; i++) {
//                    if(i == 0) {
//                        String colA = columns[i];
//                    } else if(i == 1) {
//                        String colB = columns[i];
//                    }
//                }
//            }
//        } catch (UnsupportedEncodingException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        return null;
//
//    }




//    @PostMapping("upload")
    @RequestMapping(value="/sample/upload", method=RequestMethod.POST)
    public String upload(
            @RequestParam("example1") String exampleStr,
            @RequestParam("upload_file") MultipartFile multipartFile,
            Model model
            ) throws IOException {
        model.addAttribute("originalFilename", multipartFile.getOriginalFilename());

        System.out.println("----------");

        InputStreamReader isr = new InputStreamReader(multipartFile.getInputStream(), Charset.forName("UTF-8"));
        BufferedReader br = new BufferedReader(isr);
        String line;
        while((line = br.readLine()) != null){
            System.out.println(line);;
        }

        System.out.println("----------");

        byte[] bytes = multipartFile.getBytes();
        System.out.write(bytes);

        System.out.println("----------");

        return "sample/result";
    }

    //    @PostMapping("upload")
//    @RequestMapping(value="/sample/upload", method=RequestMethod.POST)
//    public String upload(UploadForm uploadForm, Model model) {
//        model.addAttribute("originalFilename", uploadForm.getMultipartFile()
//                .getOriginalFilename());
//
//        return "sample/result";
//    }

    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = FileRequiredValidator.class)
    public @interface FileRequired {
        String message() default "{com.example.demo.validation.FileRequired.message}";

        Class<?>[] groups() default {};

        Class<? extends Payload>[] payload() default {};

        @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
        @Retention(RetentionPolicy.RUNTIME)
        @Documented
        @interface List {
            FileRequired[] value();
        }
    }
   
}