package com.pine.admin.modules.youpaiyun.controller;

import com.pine.admin.modules.youpaiyun.util.YunUploadUtils;
import com.pine.common.dto.Result;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;

/**
 * @Author: Pine
 * @Date: 2019/7/25
 * @Email:771190883@qq.com
 */

@RestController
@Api(value = "图片上传", tags = {"图片上传" })
@RequestMapping("youpai")
public class YouPaiController {

    @PostMapping(value = "/uploadFile")
    public Result uploadFile(HttpServletRequest request) {

        long startTime = System.currentTimeMillis();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();

            String paths = "";

            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    try {
                        YunUploadUtils yunUploadUtils =YunUploadUtils.getInstance();
                        String path = yunUploadUtils.uploadToUpYun(file.getInputStream(), file.getBytes());
                        paths += path + ";";
                        System.out.println("path::::" + path);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return Result.error("上传失败");
                    }
                }

            }
            return Result.success(true, paths.split(";"));
        }
        return Result.error("上传失败");
    }
}
