自己写的一个文件上传的类


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Runtime.Remoting.Messaging;
namespace uploadfiles
{
/// <summary>
/// ClassUpload 的摘要说明。
/// </summary>
/*
wenconfig中添加元素
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
<!-- maxRequestLength:指示 ASP.NET
支持的HTTP方式上载的最大字节数。该限制可用于防止因用户将大量文件传递到该服务器而导致的拒绝服务攻击。指定的大小以 KB 为单位。默认值为 4096 KB
(4 MB)。executionTimeout:指示在被 ASP.NET 自动关闭前,允许执行请求的最大秒数。在当文件超出指定的大小时,如果浏览器中会产生
DNS 错误或者出现服务不可得到的情况,也请修改以上的配置,把配置数加大。
-->
*/
/*
Machine.config中添加元素
<processModel
enable="true"
timeout="15"
idleTimeout="25"
shutdownTimeout="5"
requestLimit="1000"
requestQueueLimit="500"
responseDeadlockInterval="00:03:00"
responseRestartDeadlockInterval="Infinite"
memoryLimit="80"
webGarden="true"
maxWorkerThreads="25"
maxIoThreads="25"/>
<!--
上载大文件时,还可能会收到以下错误信息:</P><XMP> aspnet_wp.exe (PID: 1520) 被回收,因为内存消耗超过了 460 MB(可用 RAM 的百分之 60)。
</XMP>
<P>如果遇到此错误信息,请增加应用程序的 Machine.config 文件的 <processModel>元素中 memoryLimit 属性的值。
-->
*/
public class ClassUpload
{
public ClassUpload()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
private System.IO.MemoryStream m;
private System.IO.Stream fs;
private string _filename; //上传文件扩展名
private int _maxlength; //获取上传文件最大长度(字节)
private string _FilePath; //获取本地上传文件路径
private int _length = 0; //保存文件长度(字节)
private string _savepath; //获取保存路径
private string _savename; //重命名后的上传文件
private string _fullpath; //上传文件的完整目录

/// <summary>
/// 上传文件成功后文件的长度(字节)
/// </summary>
public int length
{
get
{
return _length;
}
}
/// <summary>
/// 获取保存路径
/// </summary>
public string savepath
{
get
{
return _savepath;

}
}
/// <summary>
/// 获取重命名后的上传文件
/// </summary>
public string savename
{
get
{
return _savename;

}
}
/// <summary>
/// 获取上传后文件的完整目录
/// </summary>
public string fullpath
{
get
{
return _fullpath;
}
}
/// <summary>
/// 获取本地上传文件路径
/// </summary>
public string filepath
{
get
{
return _FilePath;

}
}

/// <summary>
/// 上传文件方法
/// </summary>
/// <param name="MyFile">System.Web.UI.HtmlControls.HtmlInputFile</param>
/// <param name="savepath">设置保存上传文件的路径</param>
/// <param name="maxlength">设置上传文件的最大长度</param>
public string upload(System.Web.UI.HtmlControls.HtmlInputFile MyFile,string savepath,int maxlength)
{
this._savepath = savepath;
this._maxlength = maxlength;
//得到上载文件信息和文件流
if(MyFile.PostedFile != null)
{
System.Web.HttpFileCollection oFiles;
oFiles = System.Web.HttpContext.Current.Request.Files;

if(oFiles.Count < 1)
{
return "请选择文件!";
}

_FilePath = oFiles[0].FileName;
if(_FilePath == "" || _FilePath == null)
{
return "请选择一个文件!";
}
_filename = "."+_FilePath.Substring(_FilePath.LastIndexOf(".")+1);
//_contentlength = oFiles[0].ContentLength.ToString();

//Response.Write(FileName+FilePath);
if(oFiles[0].ContentLength>this._maxlength)
{
return "上传文件长度过大";
}
else
{
try
{
//处理上载的文件流信息。
byte[] b = new byte[oFiles[0].ContentLength];
//System.IO.Stream fs;
fs = (System.IO.Stream)oFiles[0].InputStream;
fs.Read(b, 0, oFiles[0].ContentLength);
//调用处理内存流方法UploadFile
return this.UploadFile(b,this._filename,this._savepath);
//int value = Convert.ToInt32(asy.AsyncState);

}
catch(Exception ex)
{
//Response.Write(ex.Message);
return ex.Message;
}
finally
{
fs.Close();
}
}
}
else
{
//Response.Write("请选择文件");
return "请选择文件";
}
}

private string UploadFile(byte[] fs,string FileName,string savepath)
{
try
{
//定义并实例化一个内存流,以存放提交上来的字节数组。
m = new MemoryStream(fs);
this._length = fs.Length;
//System.Web.HttpContext.Current.Server.MapPath(".") + @"\\images\"
//定义实际文件对象,保存上载的文件。
this._fullpath = this._savepath+ names()+FileName;
FileStream f = new FileStream(this._fullpath, FileMode.Create);
this._savename = names()+FileName;
//把内内存里的数据写入物理文件
m.WriteTo(f);
m.Close();
f.Close();
f = null;
m = null;

return "文件已经上传成功!";
}
catch(Exception ex)
{
return ex.Message;
}
}
//生成 (年,月,日,时,分,秒)+随机数的文件名
private string names()
{
Random rm = new Random(System.Environment.TickCount);
return System.DateTime.Now.ToString("yyyyMMddhhmmss")+rm.Next(1000,9999).ToString();
}

}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以回答这个问题。以下是一个简单的Java文件上传的工具: ```java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { public static void uploadFile(String targetUrl, String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { throw new IllegalArgumentException("File " + filePath + " does not exist"); } String boundary = Long.toHexString(System.currentTimeMillis()); String CRLF = "\r\n"; HttpURLConnection connection = (HttpURLConnection) new URL(targetUrl).openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream outputStream = connection.getOutputStream(); outputStream.write(("--" + boundary + CRLF).getBytes()); outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + CRLF).getBytes()); outputStream.write(("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName()) + CRLF).getBytes()); outputStream.write(("Content-Transfer-Encoding: binary" + CRLF).getBytes()); outputStream.write(CRLF.getBytes()); byte[] buffer = new byte[4096]; int bytesRead; InputStream inputStream = FileUploader.class.getResourceAsStream(filePath); while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } inputStream.close(); outputStream.write(CRLF.getBytes()); outputStream.write(("--" + boundary + "--" + CRLF).getBytes()); outputStream.close(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException("Failed to upload file to " + targetUrl + ", response code: " + connection.getResponseCode()); } } } ``` 这个工具使用Java的HttpURLConnection实现文件上传,可以上传指定路径下的文件到指定URL。你只需要调用`uploadFile`方法并传入目标URL和文件路径即可完成文件上传。注意,此工具仅供参考,具体实现可能需要根据你的需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值