package com.hssx.pcbms.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Author: 吴涛涛 cuiyi@itany.com
 * Date : 2019 - 10 - 16 13:47
 * Description:<描述>
 * Version: 1.0
 */
public class UploadFileToFileNameUtil {

    public static String uploadFile(MultipartFile file, String path) {
        String afterUploadFileName = "";
        if (file != null) {
            File dir = null;
            dir = new File(path);
            // D://dolphin/upload 文件上传后所存储的位置,部署到服务器上时配置服务器地址即可
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String fileName = "";
            if (file != null) {
                fileName = file.getOriginalFilename();
                System.out.println("上传文件名称" + file.getName() + "， dir = " + dir.getAbsolutePath());
                int pos = fileName.lastIndexOf(".");
                String rand = UUID.randomUUID().toString().replaceAll("-", "");
                String sufix = fileName.substring(pos);
                fileName = rand + sufix;
                afterUploadFileName = "/upload/" + fileName;
                File saveFile = new File(dir, fileName);
                try {
                    saveFile.createNewFile();
                    file.transferTo(saveFile);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return afterUploadFileName;
    }
}
