简单的文件上传服务器(上传到FastDFS服务器)

现在文件服务器使用越来越多,其中FastDFS文件服务器非常出色,可以支持分布式存储,多文件系统集群和多主机备份

环境中使用的文件服务器为172.16.100.10,其中trackerd服务和storaged服务器为同一台主机

使用到的jar包为官方提供的包,下载地址为https://sourceforge.net/projects/fastdfs/files/?source=navbar

项目环境:maven项目

项目目录树

简单的文件上传服务器(上传到FastDFS服务器)_第1张图片

 

其中pom.xml的配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>uploadServergroupId>
  <artifactId>uploadServerartifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>uploadServer Maven Webappname>
  <url>http://maven.apache.orgurl>
  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.1version>
      <scope>testscope>
    dependency>
    
    
    <dependency>
        <groupId>commons-fileuploadgroupId>
        <artifactId>commons-fileuploadartifactId>
        <version>1.3.2version>
    dependency>
    
    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>fastjsonartifactId>
        <version>1.2.31version>
    dependency>
  dependencies>
  <build>
    <finalName>uploadServerfinalName>
  build>
project>

web.xml

DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>
  
<servlet>
    <servlet-name>uploadServletservlet-name>
    <servlet-class>com.uploadServer.servlet.UploadServletservlet-class>
servlet>

<servlet-mapping>
    <servlet-name>uploadServletservlet-name>
    <url-pattern>/uploadurl-pattern>
servlet-mapping>
web-app>

uploadServer.properties

## FastDFS\u6587\u4EF6\u670D\u52A1\u5668\u7684\u5730\u5740 ##
imgServerAddress = 172.16.100.10
## FastDFS\u6587\u4EF6\u670D\u52A1\u5668\u7684\u8BBF\u95EE\u7AEF\u53E3 ##
imgServerPort = 8090

fdfs_client.conf

connect_timeout = 2
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 8090
http.anti_steal_token = no
http.secret_key = FastDFS1234567890
tracker_server=172.16.100.10:22122

UploadServlet.java

package com.uploadServer.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

import com.alibaba.fastjson.JSON;

/**
 * 功能:上传文件到FastDFS文件服务器,并返回访问链接
 * @author djoker
 *
 */
public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageClient storageClient= null;
    private StorageServer storageServer= null;
    private StorageClient1 storageClient1= null;
    private Properties properties = null;
    private InputStream imgServerConf = null;
    
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        Map putMap = new HashMap();
        
        try {
            //读取配置文件
            imgServerConf = this.getClass().getClassLoader().getResourceAsStream("uploadServer.properties");
            properties = new Properties();
            properties.load(imgServerConf);
            
            //获取FastDFS客户端的配置文件和初始化环境
            String conf = this.getClass().getClassLoader().getResource("fdfs_client.conf").getPath();
            ClientGlobal.init(conf);
            
            //从request中获取文件
            List items = upload.parseRequest(request);
            //循环文件集合
            int fileNum = 1;
            for(Iterator iter = items.iterator(); iter.hasNext();){
                FileItem item = iter.next();
                Map resMap = new HashMap();
                resMap.put("fileNum", fileNum);
                if(item.getSize() == 0){
                    resMap.put("code", -1);
                }else{
                    trackerClient = new TrackerClient();
                    trackerServer = trackerClient.getConnection();
                    storageClient1 = new StorageClient1(trackerServer, storageServer);
                    
                    //上传后返回文件路径参数
                    String[] url = storageClient1.upload_file(item.get(), item.getName().substring(item.getName().indexOf(".") + 1, item.getName().length()), null);
                    
                    //单个文件的返回信息
                    resMap.put("code", 0);
                    resMap.put("imgServerAddress", properties.getProperty("imgServerAddress"));
                    resMap.put("imgServerPort", properties.getProperty("imgServerPort"));
                    resMap.put("groupName", url[0]);
                    resMap.put("imgPath", url[1]);
                    resMap.put("fileName", item.getName());
                    resMap.put("imgUrl", "http://" + properties.getProperty("imgServerAddress") 
                                + ":" + properties.getProperty("imgServerPort") + "/" + url[0]  + "/" + url[1]);
                }
                
                putMap.put(Integer.toString(fileNum), resMap);
                fileNum++;
            }
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        //输出
        response.getWriter().println(JSON.toJSONString(putMap));
    }
    
}

 

前段jsp页面,upload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile"><br>
    <input type="file" name="myfile"><br>
    <input type="file" name="myfile"><br>
    <button type="submit">submitbutton>
form>
body>
html>

 

测试:

向文件服务器上传文件测试,启动项目输入地址http://127.0.0.1/uploadServer/upload.jsp

简单的文件上传服务器(上传到FastDFS服务器)_第2张图片

选择文件并点击submit开始上传

返回上传结果

 

访问其中的一个连接可以下载

简单的文件上传服务器(上传到FastDFS服务器)_第3张图片

 

在linux主机上查看是否删除成功

简单的文件上传服务器(上传到FastDFS服务器)_第4张图片

 

转载于:https://www.cnblogs.com/djoker/p/7067420.html

你可能感兴趣的:(简单的文件上传服务器(上传到FastDFS服务器))