c#批量上传图片到服务器示例分享
客户端代码:
/// <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));
}
}
上一篇: 基于Spring实现文件上传功能
下一篇: java 读取本地文件实例详解