文件上传插件

package com.util;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传工具类
 * @author
 *2017-05-03
 */
public class UploadFile {
    
    /**
     * 上传文件
     * @param file
     * @return file
     *
     */
    public File Uploadfile(HttpServletRequest request,MultipartFile file){
        //得到服务器地址
        
//        String path= new File(System.getProperty("user.dir")+"\\upload\\").toString();
//        if(!new File(path).exists()) {
//            new File(path).mkdirs();
//          }
        String path= request.getSession().getServletContext().getRealPath("/upload");//相对路径
        File storeDirectory = new File(path);
        if (!storeDirectory.exists()) {
            storeDirectory.mkdirs();
        }
        //原始名称.    
        String originalFilename =file.getOriginalFilename();
        //后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //
        UUID ID = UUID.randomUUID();
        String newFileName =  ID +suffix;
        //新文件
        File newFile = new File(path+"/"+newFileName);
        
        try {
            file.transferTo(newFile);
            //file.getInputStream().close();//关闭流
            return newFile;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 文件删除
     * @param file
     * @return
     */
    public String Deletefile(File file){
        
        if(file.exists()){
            try{
                if(file.delete()){
                    System.out.print("文件删除成功");
                }
                
            }catch(Exception e){
                e.getMessage();
            }
            

        }
        return null;
    }
    
}

猜你喜欢

转载自my.oschina.net/u/3288494/blog/1162313