C#進行Http上傳和下載檔案
廢話不多說,直接上程式碼
一:客戶端
1:上傳:
首先:在web.config的<appSettings></appSettings>節點中加上伺服器的地址
<add key="HttpServerUrl" value="http://IP地址:Port"/>
然後:編寫UploadController.cs和SysReturnController.cs
public class UploadController:ApiController
{
public HttpResponseMessage Upload()
{
if(HttpContext.Current.Request.Files.Count>0)
{
string savePath="d:\\";
string fileName="test.txt"
HttpPostedFile file=HttpContext.Current.Request.Files[0];
bool IsUpdate=ServerFileHelper.UploadFile(file.InputStream,savePath,fileName);
HttpContext.Current.Response.ContentType="text/plain";
var serialzer=new System.Web.Script.Serialization.JavaScriptSerializer();
var result=new{name=""};
HttpContext.Current.Response.Write(serialzer.Serialize(result));
HttpContext.Current.Response.StatusCode=200;
return new HttpResponseMessage(HttpStatusCode.OK);
}else
{
HttpContext.Current.Response.ContentType="text/plain";
var serialzer=new System.Web.Script.Serialization.JavaScriptSerializer();
var result=new{name="fail"};
HttpContext.Current.Response.Write(serialzer.Serialize(result));
HttpContext.Current.Response.StatusCode=404;
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
}
}
public class SysReturnController()
{
//下載檔案
public FileResult DownLoad()
{
Stream FileStream=ServerFileHelper.DownLoadFile("d:\\pic.jpg","pp.jpg");
if(FileStream==null)
{
return File(FileStream,"application/octed-stream","檔案不存在");
}
else
{
FileStream.Seek(0,SeekOrigin.Begin);
string realfilename="pp.jpg";
return File(FileStream,"application/octed-stream",HttpContext.Request.Browser.Browser=="IE"?Url.Encode(realfilename):realfilename);
}
}
//線上顯示圖片
public void DownLoadPic()
{
Stream FileStream=ServerFileHelper.DownLoadFile("d:\\pic.jpg","pp.jpg");
Response.ClearContent();
Response.ContentType="image/png";
Image img=Image.FormStream(FileStream);
img.Save(Response.OutputStream,ImageFormat.Png);
img.Dispose();
Response.OutputStream.Flush();
Response..OutputStream.Close();
}
}
最後,進行連線伺服器進行上傳下載
ServerFileHelper.cs
public class ServerFileHelper
{
public static bool UploadFile(Stream ST,string FilePath,string FileName)
{
string FileSaveServer=ConfigurationManager.AppSettings["HttpServerUrl"];
using(var client=new HttpClient())
using(var content=new MultipartFormDataContent())
{
byte[] bytes=new byte[ST.Length];
ST.Read(bytes,0,bytes.Length);
ST.Seek(0,SeekOrigin.Begin);
var fileContent1=new ByteArrayContent(bytes);
fileContent1.Headers.ContentDisposition=new ContentDispositionHeaderValue("attachment")
{
FileName=FileName
};
content.Add(fileContent1);
try
{
var result=client.PostAsync(FileSaveServer+"/api/upload?savepath="+FilePath,content).Result;
if(result.StatusCode.ToString()=="OK")
{
return true;
}
}
catch(Exception ex)
{
throw ex;
}
}
return false;
}
public static Stream DownLoadFile(string FilePath,string fileName)
{
string FileSaveServer=ConfigurationManager.AppSetting["HttpServerUrl"];
Stream st=null;
string actionurl=FileSaveServer+"/api/download?filepath="+FilePath+"&filename="+filename;
string customFileName=Path.GetFileName(FilePath);
try
{
WebClient wb=new WebClient();
byte [] bytes=wb.DownloadData(actionurl);
st=new MemoryStream(bytes);
wb.Dispose();
}
catch(Exception ex)
{
}
return st;
}
}
注意:進行檔案下載儲存的話要在chtml頁面中使用form表單:
function down()
{
var form=$("<form>");
form.attr('style','display:none');
form.attr('target','');
form.attr('method','post');
form.attr('action',url);
var input1=$('<input>');
input1.attr('type','hidden');
input1.attr('name','fps');
input1.attr('value','');
$('body').append(form);
form.submit();
form.remove();
}
如果要圖片線上顯示
function down(){
$("#imgPic").attr("src",url);
}
二:伺服器端
1.上傳
public class UploadController:ApiController
{
public async Task<HttpResponseMessage> PostFile(string savepath)
{
if(!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root="d:\\file";
if(!string.IsNullOrEmpty(savepath)&&savepath!="")
{
root=savepath;
if(!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
}
var provider=new MultipartFileWithExtensionStreamProvider(root);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
return new HttpResponseMessage()
{
Content=new StringContent("上傳成功")
};
}
catch(System.Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,ex);
}
}
}
2.下載
public class DownLoadController:ApiController
{
[HttpGet]
[ActionName("download")]
public HttpResponseMessage DownLoad(string filepath,string filename)
{
string root="d:\\file";
string customFileName=Path.GetFileName(filepath);
if(filename!=null&&filename!="")
{
filename=HttpContext.Current.Server.UrlDecode(filename);
customFileName=filename;
}
if(!File.Exists(filepath))
{
return new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content=new StringContent("檔案不存在")
};
}
else
{
HttpResponseMessage response=new HttpResponseMessage(HttpStatusCode.OK);
try
{
FileStream fileStream=new FileStream(filepath,FileMode.Open,FileAccess.Read,FileShare.Read);
response.Content=new StreamContent(fileStream);
response.Content.Headers.ContentType=new System.Net.Http.Header.MedisTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition=new System.Net.Http.Headers.ContentDispositionHeaderValue("attachement"){FileName=System.Web.HttpUtility.UrlEncode(customFileName.Encoding.GetEncoding("UTF-8"))};
response.Content.Header.ContentLength=new FileInfo(filepath).Length;
}
catch(Exception ex)
{
return response;
}
return response;
}
}
}
3.MultipartFileWithExtensionStreamProvider.cs
public class MultipartFileWithExtensionStreamProvider:MultipartFormDataStreamProvider
{
public MultipartFileWithExtensionStreamProvider(string rootPath):base(rootPath){}
//獲取URL中的檔名稱
public override string GetLocalFileName(System.Net.Http.Header.HttpContentHeaders headers)
{
string filepath=headers.ContentDisposition.FileName.TrimStart('\"').TrimEnd('\"');
string [] fp=filepath.Split('\\');
string name=base.GetLocalFileName(header);
if(fp.Length>0)
{
name=fp[fp.Length-1];
}
return name;
}
}