C#进行Http上传和下载文件

5 篇文章 0 订阅

废话不多说,直接上代码

一:客户端

1:上传:

首先:在web.config的<appSettings></appSettings>节点中加上服务器的地址

<add key="HttpServerUrl" value="http://IP地址:Port"/>

注意:该处的“http://IP地址:Port”是你就服务器发布之后的地址

上传url:~/api/upload

下载url:~SysReturn/DownLoad

然后:编写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 url='@Url.Content("~/SysReturn/DownLoad")';//下载文件你的action

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(){

var url='@Url.Content("~/SysReturn/DownLoadPic")';//在线显示的action

$("#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;

} 

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值