文件上傳插件

package com.util;java

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

import javax.servlet.http.HttpServletRequest;spring

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();
            }
            dom

        }
        return null;
    }
    
}工具

相關文章
相關標籤/搜索