SpringMVC 通过get请求实现文件上传

@RequestMapping(value="/imgUpload")
@ResponseBody
public FileObject addImage(@RequestParam("imgFile")MultipartFile imgFile,HttpServletRequest request) {  
String loginId = (String)session.getAttribute("LoginedID");
//取当前登录用户名称作为用户上传图片二级文件夹名称
String userName = loginId;
//转型为MultipartHttpRequest(重点的所在)  
        MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;  
        //  获得第1张图片(根据前台的name名称得到上传的文件)   
        MultipartFile imgFile1  =  multipartRequest.getFile("imgFile");
        String fileNames = imgFile1.getOriginalFilename();
        //定义一个数组,用于保存可上传的文件类型  
        List<String> fileTypes = new ArrayList<String>();  
        fileTypes.add("jpg");  
        fileTypes.add("jpeg");  
        fileTypes.add("bmp");  
        fileTypes.add("gif");
        fileTypes.add("png");
        //保存第一张图片   
        if(!(imgFile1.getOriginalFilename() ==null || "".equals(imgFile1.getOriginalFilename()))) {        
//下面调用的方法,主要是用来检测上传的文件是否属于允许上传的类型范围内,及根据传入的路径名 自动创建文件夹和文件名 
        String fileName = UploadPic.getFile(imgFile1, IMG_PATH, userName, fileTypes);  
        //替换成新的文件名
        //String newFileName = UploadPic.changeFileName(file1);
        //虚拟文件路径
        String url = IMG_PATH+userName+"/"+fileName;
        //文件原名
        String fileRealName = fileNames.substring(0, fileNames.lastIndexOf("."));
        FileObject fileObject = new FileObject();
        fileObject.setFileName(fileRealName);
        fileObject.setFilePath(url);
        System.out.println("fileRealName:"+fileObject.getFileName()+",url:"+fileObject.getFilePath());
        return fileObject;
}
        return null;

}

package com.shdatabank.tongrisk.utils;


import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


import com.shdatabank.common.ParamFileUtil;
import com.shdatabank.tongrisk.controller.UploadPicController;
import com.shdatabank.tongrisk.dto.ResultInfo;


/**
 * 图片处理工具类
 * @author zhoujunlei
 *
 */
@SuppressWarnings("unused")
public class UploadPic {
/**
* 通过传入页面读取到的文件,处理后保存到本地磁盘,并返回一个已经创建好的File 
* @param imgFile
* @param typeName
* @param brandName
* @param fileTypes
* @return
*/
public static String getFile(MultipartFile imgFile,String typeName,String brandName,List<String> fileTypes) {  
        String imageName = imgFile.getOriginalFilename();
        //获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名  
        Long time = new Date().getTime();
        String ext = imageName.substring(imageName.lastIndexOf(".")+1,imageName.length());  
        String fileName = time+"."+ext;
        //String fileName = imageName.substring(0,imageName.lastIndexOf("."))+"."+ext;
        //对扩展名进行小写转换  
        ext = ext.toLowerCase();  
           
        File file = null;  
        if(fileTypes.contains(ext)) {                      //如果扩展名属于允许上传的类型,则创建文件  
            file = UploadPic.creatFolder(typeName, brandName, fileName);  
             try {  
                imgFile.transferTo(file);                   //保存上传的文件  
            } catch (IllegalStateException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
         }  
         return fileName;  
    }
/**
* 检测与创建一级、二级文件夹、文件名这里我通过传入的两个字符串来做一级文件夹和二级文件
* 夹名称通过此种办法我们可以做到根据用户的选择保存到相应的文件夹下 
* @param typeName
* @param brandName
* @param fileName
* @return
*/
public static File creatFolder(String typeName,String brandName,String fileName) {  
String directory = ParamFileUtil.getConfigProperty("config", "grantFileDirectory");
File file = null;  
        typeName = typeName.replaceAll("/", "");               //去掉"/"  
        typeName = typeName.replaceAll(" ", "");               //替换半角空格  
        typeName = typeName.replaceAll(" ", "");               //替换全角空格  
         
        brandName = brandName.replaceAll("/", "");             //去掉"/"  
        brandName = brandName.replaceAll(" ", "");             //替换半角空格  
        brandName = brandName.replaceAll(" ", "");             //替换全角空格  
         
        File firstFolder = new File(directory + typeName);         //一级文件夹  
        if(firstFolder.exists()) {                             //如果一级文件夹存在,则检测二级文件夹  
            File secondFolder = new File(firstFolder,brandName);  
            if(secondFolder.exists()) {                        //如果二级文件夹也存在,则创建文件  
                file = new File(secondFolder,fileName);  
            }else {                                            //如果二级文件夹不存在,则创建二级文件夹  
                secondFolder.mkdir();  
                file = new File(secondFolder,fileName);        //创建完二级文件夹后,再合建文件  
            }  
        }else {                                                //如果一级不存在,则创建一级文件夹  
            firstFolder.mkdir();  
            File secondFolder = new File(firstFolder,brandName);  
            if(secondFolder.exists()) {                        //如果二级文件夹也存在,则创建文件  
                file = new File(secondFolder,fileName);  
            }else {                                            //如果二级文件夹不存在,则创建二级文件夹  
                secondFolder.mkdir();  
                file = new File(secondFolder,fileName);  
            }  
        }  
        return file;  
   }
/**
* 修改文件名为当前时间戳
* @param file
* @return
*/
public static String changeFileName(File file){
Long time = new Date().getTime();
    return time.toString()+file.getName().substring(file.getName().lastIndexOf("."));
}
/**
* 根据文件名、文件路径删除本地文件
* @param fileName
* @param userName
* @return
*/
public static boolean deleteFiles(String fileName,String userName){
//拼接出本地文件路径
String pathName =ParamFileUtil.getConfigProperty("config", "grantFileDirectory") + UploadPicController.IMG_PATH + userName + "/" + fileName;
File file2 = new File(pathName);
if (file2.isFile() && file2.exists()) {
   file2.delete();
   return true;
}
return false;
}


}



/**
 * 获取properties配置文件
 */
public class ParamFileUtil {
/** Properties对象 */
    private Properties prop;


    public static Properties loadPropertiesFromBundlefile(String bundlefile) {
        return loadPropertiesFromBundlefile(bundlefile, new Properties());
    }


    public static Properties loadPropertiesFromBundlefile(String bundlefile, Properties toprop) {
        Properties properties = toprop;
        try {
            ResourceBundle rb = ResourceBundle.getBundle(bundlefile);
            Enumeration enu = rb.getKeys();
            while (enu.hasMoreElements()) {
                String strPName = (String) enu.nextElement();
                String strPValue = null;
                if (strPName != null) {
                    strPValue = rb.getString(strPName);
                }
                if ((strPName != null) && (strPValue != null))
                    properties.setProperty(strPName, strPValue);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return properties;
    }


    public static String getConfigProperty(String propertyName,String propertyValue){
        Properties prop = loadPropertiesFromBundlefile(propertyName);
        return prop.getProperty(propertyValue);
    }
    public String getProperty(String key) {
        return getProperty(key, "");
    }


    public String getProperty(String key, String nulldef) {
        String value = getProperties().getProperty(key);
        return ((value == null) ? nulldef : value);
    }


    public String getPropertyStringValue(String key) {
        return getProperty(key);
    }


    public int getPropertyIntegerValue(String key) {
        String str = getProperty(key);
        try {
            return Integer.parseInt(str);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0;
    }


    public byte getPropertyByteValue(String key) {
        String str = getProperty(key);
        try {
            return Byte.parseByte(str);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0;
    }


    public float getPropertyFloatValue(String key) {
        String str = getProperty(key);
        try {
            return Float.parseFloat(str);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0.0F;
    }


    public double getPropertyDoubleValue(String key) {
        String str = getProperty(key);
        try {
            return Double.parseDouble(str);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0.0D;
    }


    public boolean getPropertyBooleanValue(String key) {
        String str = getProperty(key);
        try {
            return Boolean.getBoolean(str);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }


    protected void setProperty(String key, String value) {
        getProperties().setProperty(key, value);
    }


    public void removeProperty(String key) {
        getProperties().remove(key);
    }


    public Properties getProperties() {
        return this.prop;
    }


    public void clear() {
        this.prop.clear();
    }
}
















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值