簡單的文件上傳服務器(上傳到FastDFS服務器)


現在文件服務器使用越來越多,其中FastDFS文件服務器非常出色,可以支持分布式存儲,多文件系統集群和多主機備份

環境中使用的文件服務器為172.16.100.10,其中trackerd服務和storaged服務器為同一台主機

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

項目環境:maven項目

項目目錄樹

 

其中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.0</modelVersion>
  <groupId>uploadServer</groupId>
  <artifactId>uploadServer</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>uploadServer Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.2</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.31</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>uploadServer</finalName>
  </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 Application</display-name>
  
<servlet>
    <servlet-name>uploadServlet</servlet-name>
    <servlet-class>com.uploadServer.servlet.UploadServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>uploadServlet</servlet-name>
    <url-pattern>/upload</url-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<String, Object> putMap = new HashMap<String, Object>();
        
        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<FileItem> items = upload.parseRequest(request);
            //循環文件集合
            int fileNum = 1;
            for(Iterator<FileItem> iter = items.iterator(); iter.hasNext();){
                FileItem item = iter.next();
                Map<String, Object> resMap = new HashMap<String, Object>();
                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 here</title>
</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">submit</button>
</form>
</body>
</html>

 

測試:

向文件服務器上傳文件測試,啟動項目輸入地址http://127.0.0.1/uploadServer/upload.jsp

選擇文件並點擊submit開始上傳

返回上傳結果

 

訪問其中的一個連接可以下載

 

在linux主機上查看是否刪除成功

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM