后台文件上传至HDFS

不善言辞直接看代码
1.Controller层

@RequestMapping("/uploadeBankrollBill")
@ResponseBody
public String uploadeBankrollBill(@RequestParam(value = "bankrollBills", required = false)MultipartFile[] bankrollBills,HttpServletRequest request)throws IOException{
    boolean saveFiles=false;
    if(bankrollBills.length>0 ){
        String userId=((EaUser)request.getSession().getAttribute("user")).getUserid();
        Map paraMap=new HashMap();    
        paraMap.put("userId", userId);  
        paraMap.put("folder","bankrollBill"); //文件路径,文件夹名称
        saveFiles=bankrollRetrieveService.saveBankrollBillFiles(paraMap,bankrollBills);
    }
    if(saveFiles){
        return "OK";
    }
    return "error";
}

2.Service层

@Override
public boolean saveBankrollBillFiles(MultipartFile[] fileupload, Map map) {
    boolean flag = false;
    /*...省略其余代码....*/
    for (int i = 0; i < fileupload.length; i++) {
        Map addMap = new HashMap();
        String id = UUID.randomUUID().toString();
        String fileName = fileupload[i].getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        InputStream is = fileupload[i].getInputStream();
        //文件保存路径
        String path = HdfsConnect.createNewHDFSFile("/"+map.get("folder").toString().trim()+"/" + id, is);
        is.close();
        /*...省略其余代码....*/   

    }

    return flag;
}

3.HdfsConnect

public class HdfsConnect{
    public static String uri ="hdfs://192.168.1.1:8060";
    //public static String uri = PropertiesReader.getProperty("hdfs.uri");
    /*static{
        System.setProperty("HADOOP_USER_NAME", "hdfs");
    }*/
    private AllFileHandler fileHandler;
    /*...省略其余代码....*/   
    public static String createNewHDFSFile(String newFile, InputStream is) throws IOException {  
        if (StringUtils.isBlank(newFile) || null == is) {  
            return null;  
        }  
        newFile = uri + newFile;  
        Configuration config = new Configuration();  
        FileSystem hdfs = FileSystem.get(URI.create(newFile), config);  
        FSDataOutputStream os = hdfs.create(new Path(newFile));  
        byte[] b = new byte[1024];
        while(is.read(b)>0){
            os.write(b);
        }
        //os.write(content.getBytes("UTF-8"));  
        os.close();  
        hdfs.close();  
        return newFile;  
    }
}   

你可能感兴趣的:(java笔记)