package com.fos.demo.upload.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
@RequestMapping(value="/demo/upload/file")
public class DemoFileUploadController {
    
    private final static String BASE_PATH = "C:\\Users\\Administrator\\Desktop\\files\\";
    
    @ResponseBody
    @RequestMapping("/upload/files")
    public String upload(@RequestParam("file") CommonsMultipartFile[] files, HttpServletRequest request) {

        if(files == null || files.length == 0)
            return "FAIL";
        
        OutputStream os = null;
        InputStream in = null;
        try {
            
            File pf = new File(BASE_PATH);
            for (int i = 0; i < files.length; i++) {
                System.out.println("fileName---------->" + files[i].getOriginalFilename());
                if (!files[i].isEmpty()) {
                    int pre = (int) System.currentTimeMillis();
                    try {
                        if(pf.exists() == false)
                            pf.mkdirs();
                        // 拿到输出流，同时重命名上传的文件
                        File pathname = new File(BASE_PATH + new Date().getTime() + files[i].getOriginalFilename());
                        os = new FileOutputStream(pathname);
                        os = new BufferedOutputStream(os);
                        
                        // 拿到上传文件的输入流
                        in = files[i].getInputStream();
                        in = new BufferedInputStream(in);

                        // 以写字节的方式写文件
                        byte[] buf = new byte[1024];
                        int size = in.read(buf);
                        while (size != -1) {
                            os.write(buf, 0, size);
                            size = in.read(buf);
                        }
                        os.flush();
                        int finaltime = (int) System.currentTimeMillis();
                        System.out.println("处理时间（毫秒）："+(finaltime - pre));
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("上传出错");
                    } finally {
                        if(os != null){
                            try {
                                os.close();
                            } catch (Exception e2) {
                                // TODO: handle exception
                            }
                        }
                        if (in != null) {
                            try {
                                in.close();
                            } catch (Exception e2) {
                                // TODO: handle exception
                            }
                        }
                    }
                }
            }
            return "SUCCESS";
        } catch (Exception e) {
            // TODO: handle exception
        }
        
        return "FAIL";
    }
    
    @RequestMapping("/upload/multipartfile")
    public String addUser(@RequestParam("file") CommonsMultipartFile[] files, HttpServletRequest request) {

        for (int i = 0; i < files.length; i++) {
            System.out.println("fileName---------->" + files[i].getOriginalFilename());

            if (!files[i].isEmpty()) {
                int pre = (int) System.currentTimeMillis();
                try {
                    File pf = new File(BASE_PATH);
                    if(pf.exists() == false)
                        pf.mkdirs();
                    // 拿到输出流，同时重命名上传的文件
                    OutputStream os = new FileOutputStream(
                            BASE_PATH + new Date().getTime() + files[i].getOriginalFilename());
                    os = new BufferedOutputStream(os);
                    // 拿到上传文件的输入流
                    InputStream in = files[i].getInputStream();
                    in = new BufferedInputStream(in);

                    // 以写字节的方式写文件
                    byte[] buf = new byte[1024];
                    int size = in.read(buf);
                    while (size != -1) {
                        os.write(buf, 0, size);
                        size = in.read(buf);
                    }
                    os.flush();
                    os.close();
                    in.close();
                    int finaltime = (int) System.currentTimeMillis();
                    System.out.println("处理时间（毫秒）："+(finaltime - pre));
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("上传出错");
                }
            }
        }
        return "demo/upload/upload";
    }

    @RequestMapping("/upload2")
    public String upload2(HttpServletRequest request, HttpServletResponse response)
            throws IllegalStateException, IOException {
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            File pf = new File(BASE_PATH);
            if(pf.exists() == false)
                pf.mkdirs();
            while (iter.hasNext()) {
                // 记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                // 取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null) {
                    // 取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    // 如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if (myFileName.trim() != "") {
                        System.out.println(myFileName);
                        // 重命名上传后的文件名
                        String fileName = "demoUpload" + file.getOriginalFilename();
                        // 定义上传路径
                        String path = BASE_PATH + fileName;
                        File localFile = new File(path);
                        file.transferTo(localFile);
                    }
                }
                // 记录上传该文件后的时间
                int finaltime = (int) System.currentTimeMillis();
                System.out.println("处理时间（毫秒）："+(finaltime - pre));
            }

        }
        return "demo/upload/upload";
    }

    @RequestMapping("/toUpload")
    public String toUpload() {

        return "demo/upload/upload";
    }
}
