Java的新项目学成在线笔记-day8(二)

1.1.3 API接口 1.1.3.1模型类
系统的文件信息(图片、文档等小文件的信息)在mongodb中存储,下边是文件信息的模型类。
1) 模型如下:
[mw_shl_code=applescript,true]
file‐size‐threshold: 0

上传文件的临时目录

location:

最大支持文件大小

 max‐file‐size: 1MB  
 # 最大支持请求大小   
 max‐request‐size: 30MB xuecheng:   fastdfs:   
  connect_timeout_in_seconds: 5   
  network_timeout_in_seconds: 30  
   charset: UTF‐8   
  tracker_servers: 192.168.101.64:22122
@Data @ToString @Document(collection = "filesystem") public class FileSystem {   
    @Id  
   private String fileId;   
  //文件请求路径    
private String filePath;   
  //文件大小    
private long fileSize;    
//文件名称 
    private String fileName;   
//文件类型   
  private String fileType; 
    //图片宽度  
   private int fileWidth;  
   //图片高度  
   private int fileHeight;   
  //用户id,用于授权暂时不用   
  private String userId; 
    //业务key    
private String businesskey;    
//业务标签 
    private String filetag;  
  //文件元信息   
  private Map metadata;  
}
[/mw_shl_code]

说明:
fileId:fastDFS返回的文件ID。 filePath:请求fastDFS浏览文件URL。 filetag:文件标签,由于文件系统服务是公共服务,文件系统服务会为使用文件系统服务的子系统分配文件标签, 用于标识此文件来自哪个系统。
businesskey:文件系统服务为其它子系统提供的一个业务标识字段,各子系统根据自己的需求去使用,比如:课 程管理会在此字段中存储课程id用于标识该图片属于哪个课程。 metadata:文件相关的元信息。
2) collection 在mongodb创建数据库xc_fs(文件系统数据库),并创建集合 filesystem。

Java的新项目学成在线笔记-day8(二)
1.1.3.2 Api接口
在api工程下创建com.xuecheng.api.filesystem包,


[mw_shl_code=applescript,true] 

public interface FileSystemControllerApi {      
   /**    
  * 上传文件   
   * @param multipartFile 文件  
    * @param filetag 文件标签 
     * @param businesskey 业务key 
     * @param metedata 元信息,json格式  
    * @return  
    */  
   public UploadFileResult upload(MultipartFile multipartFile,     
                String filetag,        
             String businesskey,             
        String metadata); }[/mw_shl_code]

1.1.2.3 Dao
将文件信息存入数据库,主要存储文件系统中的文件路径。


[mw_shl_code=applescript,true]public interface FileSystemRepository extends MongoRepository<FileSystem,String> {   }[/mw_shl_code]
1.1.2.4 Service 
[mw_shl_code=applescript,true]@Service public class FileSystemService {       private static final Logger LOGGER = LoggerFactory.getLogger(FileSystemService.class);     
  @Value("${xuecheng.fastdfs.tracker_servers}")  
   String tracker_servers;    
@Value("${xuecheng.fastdfs.connect_timeout_in_seconds}")   
  int connect_timeout_in_seconds;   
  @Value("${xuecheng.fastdfs.network_timeout_in_seconds}")   
  int network_timeout_in_seconds;   
  @Value("${xuecheng.fastdfs.charset}")   
  String charset;  
     @Autowired  
   FileSystemRepository fileSystemRepository;   
    //加载fdfs的配置    
private void initFdfsConfig(){  
       try {      
       ClientGlobal.initByTrackers(tracker_servers);    
         ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);   
          ClientGlobal.setG_network_timeout(network_timeout_in_seconds);        
     ClientGlobal.setG_charset(charset);     
    } catch (Exception e) {   
          e.printStackTrace();       
      //初始化文件系统出错         
    ExceptionCast.cast(FileSystemCode.FS_INITFDFSERROR);     
    }   
  }   
  //上传文件  
   public UploadFileResult upload(MultipartFile file,     
                               String filetag,        
                            String businesskey,       
                             String metadata){    
       if(file == null){       
      ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);     
    }
        //上传文件到fdfs[/mw_shl_code]
[mw_shl_code=applescript,true]String fileId = fdfs_upload(file);   
      //创建文件信息对象     
    FileSystem fileSystem = new FileSystem();      
   //文件id       
  fileSystem.setFileId(fileId);   
      //文件在文件系统中的路径     
    fileSystem.setFilePath(fileId);  
       //业务标识    
     fileSystem.setBusinesskey(businesskey);    
     //标签       
  fileSystem.setFiletag(filetag);    
     //元数据      
   if(StringUtils.isNotEmpty(metadata)){   
          try {         
        Map map = JSON.parseObject(metadata, Map.class);       
          fileSystem.setMetadata(map);     
        } catch (Exception e) {       
          e.printStackTrace();        
     }    
     }   
      //名称   
      fileSystem.setFileName(file.getOriginalFilename());  
       //大小       
  fileSystem.setFileSize(file.getSize());     
    //文件类型     
    fileSystem.setFileType(file.getContentType());      
   fileSystemRepository.save(fileSystem);  
       return new UploadFileResult(CommonCode.SUCCESS,fileSystem);   
    }      
//上传文件到fdfs,返回文件id     public String fdfs_upload(MultipartFile file) {    
     try {            
//加载fdfs的配置    
         initFdfsConfig();        
     //创建tracker client     
        TrackerClient trackerClient = new TrackerClient();    
         //获取trackerServer   
          TrackerServer trackerServer = trackerClient.getConnection();     
        //获取storage      
       StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);   
          //创建storage client     
        StorageClient1 storageClient1 = new StorageClient1(trackerServer,storeStorage);     
        //上传文件      
       //文件字节     
        byte[] bytes = file.getBytes();      
       //文件原始名称      
       String originalFilename = file.getOriginalFilename();     
        //文件扩展名            
String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);     
        //文件id
            String file1 = storageClient1.upload_file1(bytes, extName, null);
[/mw_shl_code]
[mw_shl_code=applescript,true]      
      return file1;   
      } catch (Exception e) {    
         e.printStackTrace();   
      }        
return null;  
   }   }[/mw_shl_code]
1.1.2.5 Controller 
[mw_shl_code=applescript,true]@RestController @RequestMapping("/filesystem") public class FileSystemController implements FileSystemControllerApi {     @Autowired   
  FileSystemService fileSystemService;      
@Override  
   @PostMapping("/upload")   
  public UploadFileResult upload(@RequestParam("file") MultipartFile file,                  
                  @RequestParam(value = "filetag", required = true) String  filetag,                                    @RequestParam(value = "businesskey", required = false) String  businesskey,                                    @RequestParam(value = "metedata", required = false) String  metadata) {         return fileSystemService.upload(file,filetag,businesskey,metadata);  
   } }[/mw_shl_code]

1.1.2.6 测试
使用swagger-ui或postman进行测试。 下图是使用swagger-ui进行测试的界面:
Java的新项目学成在线笔记-day8(二)

猜你喜欢

转载自blog.51cto.com/13517854/2374017