由於項目中用到了大量的文件上傳和刪除,考慮到安全的因素,所以整體的思路是使用FTP從主服務器把文件資源上傳到文件服務器上。

FTP上傳到服務器的代碼如下(簡單附加一下,具體的網上很多)
public static void UploadFile(FileInfo fileInfo, string hostname, string username,
string password)
{
string target;
string targetDir = DateTime.Now.ToString("yyyy-MM-dd");
//創建文件目錄
MakeDir(targetDir,hostname,username,password);
target = Guid.NewGuid().ToString();
string URL = "FTP://" + hostname + "/" + targetDir + "/" + target;
FtpWebRequest ftp = GetRequest(URL, username, password);
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.UseBinary = true;
ftp.UsePassive = true;
ftp.ContentLength = fileInfo.Length;
const int BufferSize = 2048;
byte[] content=new byte[BufferSize];
int dataRead;
using (FileStream fs=fileInfo.OpenRead())
{
try
{
using (Stream rs = ftp.GetRequestStream())
{
do
{
dataRead = fs.Read(content, 0, BufferSize);
rs.Write(content, 0, dataRead);
} while (!(dataRead < BufferSize));
rs.Close();
}
}
catch (Exception)
{
throw;
}
finally
{
fs.Close();
Console.WriteLine("上傳成功");
}
ftp = GetRequest(URL, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
ftp.RenameTo =target+ fileInfo.Name.Substring(fileInfo.Name.IndexOf('.'));
try
{
ftp.GetResponse();
}
catch (Exception ex)
{
ftp = GetRequest(URL, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //刪除
ftp.GetResponse();
throw ex;
}
finally
{
//fileinfo.Delete();
}
// 可以記錄一個日志 "上傳" + fileinfo.FullName + "上傳到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
ftp = null;
}
}
文件上傳到服務器很簡單,接下來要通過瀏覽器的地址顯示文件(這里主要是做圖片服務器),其實可以建一個網站,然后通過網站的虛擬目錄來訪問圖片,但是個人感覺這肯定不是一種好的解決方案,於是想到了最近比較火的Nginx來做圖片代理。
安裝Nginx,我在安裝的過程中遇到了一個小問題(Windows 找不到文件Nginx...),這個錯誤是因為位置沒有定位正確,我使用的nginx-1.9.0版本,我只是定位到安裝文件的上級目錄,所以出現了這個錯誤,如果你出現了類似的錯誤,最簡單粗暴的方式就是找到nginx安裝程序,地址欄的地址直接粘出來就行。
另一個問題就是80端口被占用的情況,當我們配置完IIS后,默認端口被IIS的默認網站占用,這時候,你只需把IIS的默認網站端口修改一下即可。
安裝成功后任務管理器中會有二個進程

接下來在地址欄中輸入loaclhost,你就會發現會出現
Welcome to nginx!
Nginx安裝成功后,修改nginx.conf文件。
location / {
root html;
index index.html index.htm;
}
location /Image{
#當訪問Image 文件夾的時候指定映射到真正的物理地址
alias J:\FTPFinCloud;
#默認的圖片
index default.png;
}
#緩存圖片
location ~.*.(gif|jpg|jpeg|png|bmp|swf)${
expires 10d;
}
然后執行nginx-t,成功后接着執行nginx -s reload.這時候就可以訪問圖片了。
由於我使用的本地的所以我的地址為http://192.168.1.218/Image/2015-05-17/2015-05-17.jpg,
如果要發布到遠程服務器上,需要綁定域名時怎么辦。這時候只需在server內部配置一下即可
server
{
listen 8080;
server_name your_server_ip;
location /
{
root /;
}
access_log /usr/local/webserver/nginx/logs/nginx_access.log;
}
}
改一下 you_server_ip即可。
