com.beginner.core.utils.FileUpload.java Source code

Java tutorial

Introduction

Here is the source code for com.beginner.core.utils.FileUpload.java

Source

/*
 * Copyright 2015-9999 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.beginner.core.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

/**
* <b>??</b><br/>
* <b>??</b><br/>
* <b></b>Hsiao Lin Studio<br/>
* <b></b><br/>
* <b></b>20150521 ?6:18:18<br/>
* <b></b><br/>
* @version 1.0.0<br/>
*/
public class FileUpload {

    /**
     * 
     * @param file       
     * @param filePath    
     * @param fileName    ??
     * @return String ??
     */
    public static String fileUp(MultipartFile file, String filePath, String fileName) {
        String extName = "";
        try {
            if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            }
            copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", "");
        } catch (IOException e) {
            System.out.println(e);
        }
        return fileName + extName;
    }

    /**
     * ?upload
     * @param in          ?InputStream
     * @param dir         ??
     * @param realName      ??
     * @throws IOException   IO
     */
    private static String copyFile(InputStream in, String dir, String realName) throws IOException {
        File file = new File(dir, realName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        FileUtils.copyInputStreamToFile(in, file);
        return realName;
    }
}