file upload plugin

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;

/**
 * File upload tool class
 * @author
 *2017-05-03
 */
public class UploadFile {
    
    /**
     * Upload file
     * @param file
     * @return file
     *
     */
    public File Uploadfile(HttpServletRequest request,MultipartFile file) {
        //Get the server address
        
// 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");//relative path
        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;
    }
    
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325834717&siteId=291194637