文件上传例子

Controller层

    @RequestMapping(value = "/addUploadFile", method = RequestMethod.POST)
    public void addUploadFile(UploadFile uploadFile,HttpServletRequest request,HttpServletResponse response) throws Exception {
		//创建一个通用的多部分解析器.  
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
        request.getSession().getServletContext());
        //设置编码 
        commonsMultipartResolver.setDefaultEncoding("utf-8");
        //判断 request 是否有文件上传,即多部分请求...  
        if (commonsMultipartResolver.isMultipart(request)) {//有文件上传  
        	//转换成多部分request  
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //根据转换成的多部分request,获取文件名称  
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile files = multiRequest.getFile(iter.next().toString());
                long fileS=files.getSize();
                //获取文件大小
                String fsizes= FileAttUtils.formetFileSize(fileS);
                uploadFile= allSearchService.addUploadFile(request,
                		files, uploadFile,fsizes);
                //注释部分是创建文件索引,可以忽略
               /* List list=new ArrayList<>();
	                if(uploadFile !=null){//如果文件不是null,获取文件id
	                	list.add(uploadFile);
	                	ThreadPoolManager thread=new ThreadPoolManager();
		 		 		thread.execute(new FileTask(list));//生成全文索引
	                }*/
                }
            }
           writeJSON(response, uploadFile);
           
    	}

Service层

      @Override
	public UploadFile addUploadFile(HttpServletRequest request, MultipartFile files,
			UploadFile uploadFile,String fsizes) {
		try {
			//获取文件名称
			String newName = files.getOriginalFilename();
			//获取文件名称(从.开始截取到最后)的具体格式(例: .doc格式)
			String name=files.getOriginalFilename().substring(files.getOriginalFilename()
					   .lastIndexOf("."));
			String fPath=FileAttUtils.getPath("0000", "A002");
			String filepaths=fPath+File.separator+newName;
			String path=FileAttUtils.getFilePath(fPath)+File.separator+newName;
			File file1= new File(path);
			//上传文件
			files.transferTo(file1);
			//将文件信息保存到数据库中
			uploadFile.setId(BasicTool.getUUID());
			uploadFile.setFilename(newName);
			uploadFile.setFilepath(filepaths);
			uploadFile.setFiletype(name);
			uploadFile.setFilesize(fsizes);
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			uploadFile.setDatetimes(df.format(new Date()));
			int count=allSearchServiceMapper.addUploadFile(uploadFile);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return uploadFile;
	}

文件工具类

 /**
     * 文件大小转换
     * 
     * @param fileS
     *            文件长度,以字节为单位
     * @return 返回文件长度 字节、KB、MB、GB
     */
    public static String formetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + " B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + " KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + " MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + " GB";
        }
        return fileSizeString;
    }
    
   /**
     * 创建文件路径
     */
    public static String getPath(String fondsCode,String arcClass){
		Date currentTime = new Date();
		String dateString = formatter.format(currentTime);
		String path=(fondsCode+File.separator+arcClass+File.separator+dateString);
		return path;
    }
      /**
     * 指定文件磁盘地址
     */
    public static String getFilePath(String filePath){
        // SysParamInits.ARRANGE_FILE_PATH配置文件中定义磁盘地址  例:D:\file文件夹下
		File file =new File(SysParamInits.ARRANGE_FILE_PATH+File.separator+filePath);
		if(!file.exists()){
				file.mkdirs();
		}
		return file.getPath();
	}

你可能感兴趣的:(java)