/*
 * @Author: Kane
 * @Date: 2023-01-22 23:11:26
 * @LastEditors: Kane
 * @LastEditTime: 2023-01-24 00:55:08
 * @FilePath: \AdminSys\src\main\java\com\cpic\xim\web\controllers\FileUpload\FileUpload.java
 * @Description: 用于接受上传文件的Controller。
 * 
 * Copyright (c) ${2022} by Kane, All Rights Reserved. 
 */

package com.cpic.xim.web.controllers.FileUpload;

import java.io.File;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
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;

@SuppressWarnings( "unused" )
@Controller
@RequestMapping( path = "/file" )
public class FileUpload
{
    /*****************************************************
     * 接收上传文件，并保存到临时目录：
     * 1、临时目录下再用sessionID作为子目录保存文件。
     * 2、保存时不更改文件名，会覆盖同名文件。
     * 3、MultipartFile参数形参名称必须和请求form中file标签的name属性一致，否则值为null。
     * 4、返回值为接收结果和文件保存路径。
     *****************************************************/
    @RequestMapping( path = "/file-upload.do" )
    @ResponseBody
    public FileUploadResult getUploadFile( @RequestParam( "task-name" ) String taskName,
            @RequestParam( "file" ) MultipartFile[] files, HttpServletRequest request )
    {
        // session id用来创建临时目录，避免重复
        String sessionID = request.getSession().getId();
        FileUploadResult result = new FileUploadResult();
        Vector<String> fileNames = new Vector<String>();
        int fileCount = files.length;

        // 防御验证
        if ( files.length == 0 )
        {
            result.setSuccess( false );
            result.setMessage( "此接口用于上传文件!" );

            return result;
        }

        result.setSuccess( true );
        result.setMessage( "上传成功!" );

        for ( MultipartFile file : files )
        {
            // 检查文件长度，如果为0则跳过
            if ( file.isEmpty() )
            {

                continue;
            }

            // 保存文件到临时目录
            String filePath =
                    request.getServletContext().getRealPath( "/temp/upload/" + sessionID );
            String fileName = file.getOriginalFilename();
            File destFile = new File( filePath, fileName );

            fileNames.add( file.getOriginalFilename() );
        }

        result.setFileList( fileNames );

        return result;
    }
}
