欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#批量上传图片到服务器示例分享

程序员文章站 2023-12-20 11:46:10
客户端代码: 复制代码 代码如下:/// /// 批量上传图片/// ///

客户端代码:

复制代码 代码如下:

/// <summary>
/// 批量上传图片
/// </summary>
/// <param name="srcurl">服务器路径</param>
/// <param name="imagespath">图片文件夹路径</param>
/// <param name="files">图片名称</param>
public void uploadfile(string srcurl, string imagespath, list<string> files)
{
    int count = 1;
    foreach (string imagename in files)
    {
string name = imagename;
string url = null;
//+  加号特殊处理
if (name.contains("+"))
{
    url = srcurl + "name=" + name.replace("+", "%2b");
}
else
{
    url = srcurl + "name=" + name;
}

filestream fs = new filestream(imagespath + name, filemode.open);
byte[] data = new byte[fs.length];
fs.read(data, 0, data.length);
fs.close();

httpwebrequest request = (httpwebrequest)webrequest.create(url);
request.contenttype = "image/jpeg";
request.method = "post";
encoding encoding = encoding.utf8;
request.contentlength = data.length;
stream requeststream = request.getrequeststream();
requeststream.write(data, 0, data.length);
requeststream.close();


httpwebresponse response = (httpwebresponse)request.getresponse();
streamreader streamreader = new streamreader(response.getresponsestream(), encoding);
string retstring = streamreader.readtoend();
streamreader.close();

console.writeline((count++) + "/" + files.count);

    }
}

服务器端代码:

复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.net;
using system.text;
using system.io;

public partial class upload : system.web.ui.page
{

protected void page_load(object sender, eventargs e)
{
string fpath = server.mappath("服务器端图片存储的虚拟目录名称");//得到虚拟目录的真实路径//检查存储目录
if (!directory.exists(fpath))
{
    directory.createdirectory(fpath);
}
string name = request.querystring["name"];//得到文件名
httputility.urlencode(name, encoding.getencoding("utf-8"));

if (name != null)
{
    if (!file.exists(fpath + name))
    {
system.io.stream stream = request.inputstream;
byte[] buffer = new byte[stream.length];
filestream fs = null;
try
{
    fs = new filestream(fpath + name, filemode.create);
    while ((stream.read(buffer, 0, buffer.length)) > 0)
    {
fs.write(buffer, 0, buffer.length);
    }
}
catch (ioexception ioe)
{
    response.write(ioe);
}
finally
{
    if (fs != null)
    {
fs.close();
 }
    stream.close();
}
response.write(name + "<br>");
response.write(file.exists(fpath + name) + "<br>");
}
}
response.write("上传完毕" + directory.exists(fpath) + path.getfullpath(fpath));
}
}

上一篇:

下一篇: