继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

追加java实现上传文件的方法

爱总结的小仙女
关注TA
已关注
手记 47
粉丝 57
获赞 437

导jar包
图片描述

上传多个文件的方法

 /**
     * 上传多个文件
     * 传入参数:上传路径(String),上传类型(String数组),文件的map(fileMap)
     * 返回参数:boolean
     */
    public static boolean uploadFile(String uploadDir,String[] types,HttpServletRequest request){
        String upPath=uploadDir+FileOperateUtil.UPLOADDIR;
        String fileName = ""; 
         String storeName="";
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;  
        Map<String, MultipartFile> fileMap = mRequest.getFileMap();
        Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, MultipartFile> entry = it.next();  
            MultipartFile mFile = entry.getValue();
            fileName = mFile.getOriginalFilename();  
            storeName = rename(fileName);
            /*遍历文件类型数组,类型匹配则上传文件返回true,否则上传失败返回false*/
            for(String type:types){
                if(getSuffix(storeName).equals(type)){
                    try {
                        FileUtils.copyInputStreamToFile(mFile.getInputStream(), new File(upPath,storeName));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return true;
                }else{
                    continue ;
                }

            }

        }
        return false;
    } 

上传单个文件的方法

 /**
     * 上传单个文件
     * 上传路径 upPath
     */
    public static String uploadOneFile(String upPath,String[] types,HttpServletRequest request){
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;  
            MultipartFile mFile = mRequest.getFile("file");
            String fileName = mFile.getOriginalFilename();  
            String storeName = rename(fileName);
            /*遍历文件类型数组,类型匹配则上传文件返回true,否则上传失败返回false*/
            for(String type:types){
                if(getSuffix(storeName).equals(type)){
                    try {
                        FileUtils.copyInputStreamToFile(mFile.getInputStream(), new File(upPath,storeName));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return storeName;
                }
            }
        return "fault";
    } 

其中上述的给文件重新命名的方法(rename)以及 根据转换后的文件名得到上传文件的后缀,即文件的类型的方法(getSuffix)代码如下


    /** 
     * 将上传的文件进行重命名      采用当前日期+随机数
     */  
    public static String rename(String name) {  

        Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));  
        Long random = (long) (Math.random() * now);  
        String fileName = now + "" + random;  

        if (name.indexOf(".") != -1) {  
            fileName += name.substring(name.lastIndexOf("."));
        }  
        return fileName;  
    }  

   /**
    * 根据转换后的文件名得到上传文件的后缀,即文件的类型
    */
    public static String getSuffix(String storename){
        String[] filename=storename.split("\\.");
        String suffix=filename[filename.length-1];
        return suffix;
    }

java实现文件上传的另一种方式

//util工具类
package com.ce.common.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class UploadFiles {
    // 获取上传附件列表
    @SuppressWarnings("rawtypes")
    public Set<MultipartFile> getFileSet(HttpServletRequest request) {

        /*MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);*/

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Set<MultipartFile> fileset = new LinkedHashSet<MultipartFile>();
        for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
            String key = (String) it.next();
            MultipartFile file = multipartRequest.getFile(key);
            if (file.getOriginalFilename().length() > 0) {
                fileset.add(file);
            }
        }
        return fileset;
    }

    /**
     * 上传附件
     * 
     * @param file
     *            上传文件
     * @param ctxPath
     *            服务器绝对路径
     * @return 返回值 map<fileName,fileUrl>
     * @throws IOException
     */
    public Map<String, String> uploadFileAndCallback(MultipartFile file, String ctxPath, String path)
            throws IOException {
        String filename = file.getOriginalFilename();
        if(FileUtil.checkFileImage(filename)){
            String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String lastFileName = System.currentTimeMillis() + extName;
            String resource_name = OperatePropertiesUtil.readValue("config.properties", "upload.path");
            // String path = DateFormatUtil.DateToString(date, "yyyMMdd");
            String fileFullPath =  resource_name  + path + File.separator;
            String tempPath = resource_name + "temp";
            File dirPath = new File(fileFullPath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File repository = new File(tempPath);
            if(!repository.exists()){
                repository.mkdirs();
            }

            String imagesUrl = OperatePropertiesUtil.readValue("config.properties", "imagesUrl");
            FileCopyUtils.copy(file.getBytes(), new File(fileFullPath + lastFileName));
            Map<String, String> pathMap = new HashMap<String, String>();
            pathMap.put("url", "http://" + imagesUrl + "/" + path + "/" + lastFileName);
            return pathMap;
        }else{
            return null;
        }

    }

    /**
     * 上传附件
     * 
     * @param file 上传文件
     * @param ctxPath
     *            服务器绝对路径
     * @return 返回值 map<fileName,fileUrl>  对文件进行重命名
     * @throws IOException
     */
    public Map<String, String> uploadFileAndCallback_(MultipartFile file, String path) throws IOException {
        String filename = file.getOriginalFilename();
        if(FileUtil.checkFileImage(filename)){
            String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String lastFileName = System.currentTimeMillis() + extName;
            String uploadPath = OperatePropertiesUtil.readValue("config.properties", "upload.path");
            String fileFullPath = uploadPath + path + File.separator;
            String tempPath = uploadPath + "temp";
            File dirPath = new File(fileFullPath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File repository = new File(tempPath);
            if(!repository.exists()){
                repository.mkdirs();
            }
            FileCopyUtils.copy(file.getBytes(), new File(fileFullPath + lastFileName));
            Map<String, String> pathMap = new HashMap<String, String>();
            String imagesUrl = "http://" + OperatePropertiesUtil.readValue("config.properties", "imagesUrl");
            pathMap.put("url",imagesUrl + "/" + path + "/" + lastFileName);
            return pathMap;
        } else {
            return null;
        }
    }

    public Map<String, String> uploadExcelAndCallback_(MultipartFile file, String path) throws IOException {
        String filename = file.getOriginalFilename();
        if(FileUtil.checkFileExcel(filename)){
            String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String lastFileName = System.currentTimeMillis() + extName;
            String uploadPath = OperatePropertiesUtil.readValue("config.properties", "upload.path");
            String fileFullPath = uploadPath + path + File.separator;
            String tempPath = uploadPath + "temp";
            File dirPath = new File(fileFullPath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File repository = new File(tempPath);
            if(!repository.exists()){
                repository.mkdirs();
            }
            FileCopyUtils.copy(file.getBytes(), new File(fileFullPath + lastFileName));
            Map<String, String> pathMap = new HashMap<String, String>();
            String imagesUrl = "http://" + OperatePropertiesUtil.readValue("config.properties", "imagesUrl");
            pathMap.put("url",imagesUrl + "/" + path + "/" + lastFileName);
            pathMap.put("lastFileName",lastFileName);
            pathMap.put("fileFullPath",fileFullPath);
            return pathMap;
        } else {
            return null;
        }
    }

    /**
     * 上传附件
     * 
     * @param file 上传文件
     * @param ctxPath
     *            服务器绝对路径
     * @return 返回值 map<fileName,fileUrl>  对文件进行重命名
     * @throws IOException
     */
    public Map<String, String> uploadFileAndCallback_img(MultipartFile file, String path) throws IOException {
        String filename = file.getOriginalFilename();
        if(FileUtil.checkFileImage(filename)){
            String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String lastFileName = System.currentTimeMillis() + extName;
            String uploadPath = OperatePropertiesUtil.readValue("config.properties", "upload.path");
            String fileFullPath = uploadPath + path + File.separator;
            String tempPath = uploadPath + "temp";
            File dirPath = new File(fileFullPath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File repository = new File(tempPath);
            if(!repository.exists()){
                repository.mkdirs();
            }
            FileCopyUtils.copy(file.getBytes(), new File(fileFullPath + lastFileName));
            Map<String, String> pathMap = new HashMap<String, String>();
            String imagesUrl = "http://" + OperatePropertiesUtil.readValue("config.properties", "imagesUrl");
            pathMap.put("url",imagesUrl + "/" + path + "/" + lastFileName);
            return pathMap;
        } else {
            return null;
        }
    }

    /**
     * 上传附件
     * 
     * @param file 上传文件
     * @param ctxPath
     *            服务器绝对路径
     * @return 返回值 map<fileName,fileUrl>  对文件进行重命名
     * @throws IOException
     */
    public Map<String, String> uploadFileAndCallback_video(MultipartFile file, String path) throws IOException {
        String filename = file.getOriginalFilename();
        if(FileUtil.checkFileVideo(filename)){
            String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String lastFileName = System.currentTimeMillis() + extName;
            String uploadPath = OperatePropertiesUtil.readValue("config.properties", "upload.path");
            String fileFullPath = uploadPath + path + File.separator;
            String tempPath = uploadPath + "temp";
            File dirPath = new File(fileFullPath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File repository = new File(tempPath);
            if(!repository.exists()){
                repository.mkdirs();
            }
            FileCopyUtils.copy(file.getBytes(), new File(fileFullPath + lastFileName));
            Map<String, String> pathMap = new HashMap<String, String>();
            String imagesUrl = "http://" + OperatePropertiesUtil.readValue("config.properties", "imagesUrl");
            pathMap.put("url",imagesUrl + "/" + path + "/" + lastFileName);
            return pathMap;
        } else {
            return null;
        }
    }

    /**
     * 上传附件
     * 
     * @param file 上传文件
     * @param ctxPath
     *            服务器绝对路径
     * @return 返回值 map<fileName,fileUrl>  对文件进行重命名
     * @throws IOException
     */
    public Map<String, String> uploadFileAndCallback_audio(MultipartFile file, String path) throws IOException {
        String filename = file.getOriginalFilename();
        if(FileUtil.checkFileAudio(filename)){
            String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String lastFileName = System.currentTimeMillis() + extName;
            String uploadPath = OperatePropertiesUtil.readValue("config.properties", "upload.path");
            String fileFullPath = uploadPath + path + File.separator;
            String tempPath = uploadPath + "temp";
            File dirPath = new File(fileFullPath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File repository = new File(tempPath);
            if(!repository.exists()){
                repository.mkdirs();
            }
            FileCopyUtils.copy(file.getBytes(), new File(fileFullPath + lastFileName));
            Map<String, String> pathMap = new HashMap<String, String>();
            String imagesUrl = "http://" + OperatePropertiesUtil.readValue("config.properties", "imagesUrl");
            pathMap.put("url",imagesUrl + "/" + path + "/" + lastFileName);
            return pathMap;
        } else {
            return null;
        }
    }

    /****
     * 
    * <p>方法名称: uploadFileAndCallback_2|描述: 上传图片</p>
    * @param file   上传文件  
    * @param ctxPath   绝对路径
    * @param path      路径
    * @param newFileName   新文件名
    * @return
    * @throws IOException
     */
    public Map<String, String> uploadFileAndCallback_2(MultipartFile file, String ctxPath, String path,String newFileName) throws IOException {
        String filename = file.getOriginalFilename();

        if(FileUtil.checkFileImage(filename)){
            String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String lastFileName = newFileName + extName;
            String resource_name = OperatePropertiesUtil.readValue("config.properties", "upload.path");
            // String path = DateFormatUtil.DateToString(date, "yyyMMdd");
            String fileFullPath =  resource_name  + path + File.separator;
            String tempPath = resource_name + "temp";
            File dirPath = new File(fileFullPath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File repository = new File(tempPath);
            if(!repository.exists()){
                repository.mkdirs();
            }
            FileCopyUtils.copy(file.getBytes(), new File(fileFullPath + lastFileName));
            Map<String, String> pathMap = new HashMap<String, String>();
            String imagesUrl = "http://" + OperatePropertiesUtil.readValue("config.properties", "imagesUrl");
            pathMap.put("url",imagesUrl + File.separator + path + File.separator + lastFileName);
            return pathMap;
        }else{
            return null;
        }
    }

    /****
     * 
    * <p>方法名称: uploadFileAndCallback_2|描述: 上传图片</p>
    * @param file   上传文件  
    * @param ctxPath   绝对路径
    * @param path      路径
    * @param newFileName   新文件名
    * @return
    * @throws IOException
     */
    public Map<String, String> uploadFileAndCallback(MultipartFile file, String path) throws IOException {
        String filename = file.getOriginalFilename();

        if(FileUtil.checkFileImage(filename)){
            String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String lastFileName = System.currentTimeMillis()  + extName;
            String resource_name = OperatePropertiesUtil.readValue("config.properties", "upload.path");
            String fileFullPath =  resource_name  + path + File.separator;
            String tempPath = resource_name + "temp";
            File dirPath = new File(fileFullPath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File repository = new File(tempPath);
            if(!repository.exists()){
                repository.mkdirs();
            }
            FileCopyUtils.copy(file.getBytes(), new File(fileFullPath + lastFileName));
            Map<String, String> pathMap = new HashMap<String, String>();
            pathMap.put("filePath", "/" + path + "/" + lastFileName);
            return pathMap;
        }else{
            return null;
        }
    }

    /**
     * 验证图片文件格式
     * 
     * @param file
     * @return
     */
    public boolean validateFile(MultipartFile file) {
        if (file.getSize() < 0 || file.getSize() > 2000000)
            return false;
        String filename = file.getOriginalFilename();
        String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
        String imagesExt = OperatePropertiesUtil.readValue("config.properties", "file.upload.image");
        boolean flag = false;
        for(String ext : imagesExt.split(";")){
            if(extName.equals(ext)){
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 验证视频文件格式
     * 
     * @param file
     * @return
     */
    public boolean validateAudioFile(MultipartFile file) {
        if (file.getSize() < 0 || file.getSize() > 2000000)
            return false;
        String filename = file.getOriginalFilename();
        String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
        String exts = OperatePropertiesUtil.readValue("config.properties", "file.upload.audio");
        boolean flag = false;
        for(String ext : exts.split(";")){
            if(extName.equals(ext)){
                flag = true;
            }
        }
        return flag;
    }
}
//java类调用上传的方法(java类必须要继承UploadFiles)
    public Object importData(ModelMap map,String permissionItemId,HttpServletRequest request) throws Exception{
        //文件要上传的路径
        // 获取附件集合
        Set<MultipartFile> mfs = getFileSet(request);
        Map<String, String> pathMap = new HashMap<String, String>();
        // 获取模板存放附件地址
        String path = “D:/tomcat/apache-eclipse-tomcat-7.0.68/webapps/xypt_im/upload/”;//文件要上传的路径
        // 保存附件 返回url name
        for (MultipartFile mf : mfs) {
            pathMap = uploadExcelAndCallback_(mf, path);
            // 拿到的imgPath就是图片的相对于contextPath的存储路径了
            //paths.add(pathMap);
        }
        if (pathMap==null) {
            return JSONUtil.msgJson("err", "上传失败!");
        }else{

            return JSONUtil.msgJson("success", "上传成功!");
        }
    }   
打开App,阅读手记
3人推荐
发表评论
随时随地看视频慕课网APP