Neste artigo, descrevemos como usar o Spring Boot para fazer upload de arquivos para o sistema de arquivos distribuído FastDFS.
Este projeto será construído com base no projeto anterior.
1. Configuração do pacote POM
Usamos a versão mais recente da Spring Boot 1.5.9, o JDK usa 1.8, tomcat8.0.
<Depencency> <voundid> org.csource </foupiD> <stifactId> fastdfs-client-java </artifactId> <versão> 1.27-snapshot </versão </dependence>
Adicionado o pacote FastDFS-Client-Java para ligar para APIs relacionadas ao FastDFS.
2. Arquivo de configuração
Adicione o arquivo fdfs_client.conf no diretório de recursos
connect_timeout = 60network_timeout = 60charset = UTF-8http.tracker_http_port = 8080http.anti_steal_token = nohttp.secret_key = 123456tracker_server = 192.168.53.85:22122tracker_server = 192.168.53.86:22122
O arquivo de configuração define o tempo de tempo limite da conexão, o formato de codificação, o endereço Tracker_server e outras informações.
Referência para detalhes: fastdfs-client-java
3. Encapsular a classe de ferramentas de upload FastDFS
Encapsular FastDFSFile, e as informações básicas do arquivo incluem nome de arquivo, conteúdo, tipo de arquivo, autor, etc.
classe pública fastdfsfile {private string name; Byte privado [] conteúdo; Private String ext; String privada md5; Autor de String Private; // omita getter e setterEncapsular a classe FastDfSclient, incluindo métodos comumente usados, como upload, download e exclusão.
Primeiro, leia as informações de configuração correspondentes quando a classe for carregada e inicialize.
static {try {string filepath = new ClassPathResource ("fdfs_client.conf"). getFile (). getAbsolutepath () ;; Clientglobal.init (filepath); trackerClient = new TrackerClient (); trackerServer = trackerClient.getConnection (); storageServer = rastrearclient.getStorestorage (rastrearerver); } Catch (Exceção e) {Logger.error ("Fastdfs Client Init Fail!", E); }}Upload de arquivo
public static string [] upload (arquivo fastdfsfile) {logger.info ("Nome do arquivo:" + file.getName () + "comprimento do arquivo:" + file.getContent (). length); NameValuepair [] meta_list = new nameValuepair [1]; meta_list [0] = new nameValuepair ("autor", file.getauthor ()); long startTime = System.currenttimemillis (); String [] uploadResults = null; tente {storageclient = new storageclient (rastrearerver, storageServer); uploadResults = storageclient.upload_file (file.getContent (), file.geText (), meta_list); } catch (ioexception e) {Logger.error ("Exceção de IO ao carregar o arquivo:" + file.getName (), e); } catch (Exceção e) {Logger.error ("Exceção não IO ao fazer o upload do arquivo:" + file.getName (), e); } logger.info ("upload_file hime usado:" + (system.currenttimemillis () - starttime) + "ms"); if (uploadResults == null) {Logger.error ("Falha no arquivo de upload, código de erro:" + storageclient.getErrorCode ()); } String groupName = uploadResults [0]; String remotefilename = uploadResults [1]; Logger.info ("Faça o upload do arquivo com sucesso !!!" + "group_name:" + groupName + ", remotefilename:" + "" + remotefileName); Retornar o uploadResults;}Use o storageclient do cliente fornecido pelo FastDFS para fazer upload de arquivos e, finalmente, retorne o resultado do upload.
Obtenha informações de arquivo com base no nome do grupo e no nome do arquivo.
public static fileInfo getfile (string groupName, string remotefilename) {try {storageClient = new storageclient (rastrearerver, storageServer); return storageclient.get_file_info (groupname, remotefilename); } catch (ioexception e) {Logger.error ("Exceção de IO: Obtenha o arquivo do Fast DFS falhou", e); } catch (Exceção e) {Logger.error ("Exceção não IO: Obtenha o arquivo do Fast DFS falhou", e); } retornar nulo;}Baixe o arquivo
public static inputStream DownFile (String GroupName, String RemoteFilename) {Try {storageClient = new Storageclient (rastrearerver, storageServer); byte [] fileByte = storageclient.download_file (groupName, remotefilename); InputStream ins = new ByteArrayInputStream (FileByte); retornar ins; } catch (ioexception e) {Logger.error ("Exceção de IO: Obtenha o arquivo do Fast DFS falhou", e); } catch (Exceção e) {Logger.error ("Exceção não IO: Obtenha o arquivo do Fast DFS falhou", e); } retornar nulo;}Excluir arquivos
public static void DeleteFile (String GroupName, String RemoteFilename) lança Exceção {storageclient = new Storageclient (rastrearerver, storageServer); int i = storageclient.delete_file (groupName, remotefilename); Logger.info ("Exclua o arquivo com sucesso !!!" + i);}Ao usar o FastDFS, basta chamar o método correspondente do FastDfSclient.
4. Escreva a classe de controle de upload
Leia as informações do arquivo do MultipartFile e faça o upload do arquivo no cluster FastDFS usando o FastDfSclient.
public string savefile (multipartfile multipartfile) lança ioexception {string [] fileAbsolutepath = {}; String filename = multipartfile.getoriginalfilename (); String ext = filename.substring (filename.lastIndexof (".") + 1); byte [] file_buff = null; InputStream inputStream = multipartFile.getInputStream (); if (inputStream! = null) {int len1 = inputStream.Available (); file_buff = novo byte [len1]; inputStream.read (file_buff); } inputStream.close (); FASTDFSFILE FILE = new FastDFSFile (nome do arquivo, file_buff, ext); tente {fileAbsolutepath = fastdfsclient.upload (arquivo); // upload para fastdfs} catch (Exceção e) {Logger.error ("Upload do arquivo de exceção!", e); } if (fileAbsolutepath == null) {Logger.error ("Falha no arquivo de upload, envie novamente novamente!"); } String path = fastdfsclient.gettrackerurl ()+fileAbsolutepath [0]+"/"+FileAbsolutePath [1]; caminho de retorno;}Solicite controle, ligue para o método acima savefile ().
@PostMapping ("/upload") // nova anotação desde 4.3public string singlefileUpload (@RequestParam ("FILE") FILETFILE, Redirectattributes RedirectatTrributes) {if (file.isempty ()) {RedirectTrributes.adflashAtTrttTrttTtTrtão; retornar "Redirecionar: uploadStatus"; } tente {// Obtenha o arquivo e salve -o em algum lugar da String PATH = SAVEFILE (FILE); redirectattributes.addflashattribute ("mensagem", "você carregou com sucesso '" + file.getoriginalfileName () + "'"); redirectattributes.addflashattribute ("caminho", "pato de arquivo url '" + path + "'"); } catch (Exceção e) {Logger.error ("Falha no arquivo de upload", e); } Retorne "Redirect:/UploadStatus";}Depois que o upload for bem -sucedido, exiba o caminho do arquivo para a página e as renderizações são as seguintes:
Visite este URL no seu navegador e você pode ver que ele é exibido com sucesso através do FastDFS:
Isso é feito usando a bota de primavera para integrar o FastDFS.
Código de amostra - Github
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.