我的 plupload 代码工作正常。上传成功后我需要将文件名和文件大小保存到表中。我怎么能用 c# 在 asp.net 中做到这一点,我搜索了很多,但我没有找到任何帮助。
我的工作代码在这里
<div style="text-align: center">
<img src="images/upload_images.png" style="width: 960px" />
</div>
<div id="runtimediv">No runtime found.</div>
<div id="uploaderdiv">
<p>Your browser does not have HTML5, Flash, or Silverlight support.</p></div>
脚本
// Convert divs to queue widgets when the DOM is ready
$(function () {
$("#uploaderdiv").plupload({
runtimes: 'html5,flash,silverlight,html4,gears,browserplus',
url: 'https://s3.amazonaws.com/<%=BucketName%>',
max_file_size: '5000mb',
multipart: true,
multipart_params: {
'key': '<%=foldername%>/${filename}', // use filename as a key
'Filename': '${filename}', // adding this to keep consistency across the runtimes
'acl': 'public-read',
//'Content-Type': 'image/jpeg',
'success_action_status': '201',
'AWSAccessKeyId': '<%=AWSAccessKeyID%>',
'policy': '<%=PolicyDocument%>',
'signature': '<%=PolicyDocumentSignature%>'
},
preinit: {
Init: function (up, params) {
$('#runtimediv').html("<div>Current runtime: " + params.runtime + "</div>");
}
},
// !!!Important!!!
// this is not recommended with S3, since it will force Flash runtime into the mode, with no progress indication
//resize : {width : 800, height : 600, quality : 60}, // Resize images on clientside, if possible
// optional, but better be specified directly
file_data_name: 'file',
// re-use widget (not related to S3, but to Plupload UI Widget)
multiple_queues: true,
// Specify what files to browse for
//filters : [
// {title : "JPEG files", extensions : "jpg"}
//],
// Flash settings
flash_swf_url: '/plupload_v1.5.4/js/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url: '/plupload_v1.5.4/js/plupload.silverlight.xap'
});
});
C# 代码
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//HttpContext.Current.Response.Cache.SetNoServerCaching();
//HttpContext.Current.Response.Cache.SetNoStore();
if (Session["username"] == crs.username && crs.username != null && crs.username != "")
{
AWSAccessKeyID = crs.AWSAccessKey; //** put your value here **
AWSSecretAccessKey = crs.AWSSecretKey; //** put your value here **
BucketName = crs.BUCKET_NAME; //** put your value here **
// crs.foldname = "user130";
foldername = crs.foldname;
DateTime ExpirationDate;
ExpirationDate = DateTime.UtcNow.AddMinutes(60);
PolicyDocument = "";
PolicyDocument += "{";
PolicyDocument += " \"expiration\": \"" + ExpirationDate.ToString("s") + ".000Z\",";
PolicyDocument += " \"conditions\": [";
PolicyDocument += " {\"bucket\": \"" + BucketName + "\"},";
PolicyDocument += " {\"acl\": \"public-read\"},";
PolicyDocument += " {\"success_action_status\": \"201\"},";
//PolicyDocument += " [\"starts-with\", \"$Content-Type\", \"image/\"],";
PolicyDocument += " [\"starts-with\", \"$Filename\", \"\"],";
PolicyDocument += " [\"starts-with\", \"$name\", \"\"],";
PolicyDocument += " [\"starts-with\", \"$key\", \"\"],";
PolicyDocument += " ]";
PolicyDocument += "}";
Byte[] ByteArray;
ByteArray = System.Text.Encoding.UTF8.GetBytes(PolicyDocument);
Response.Write(ByteArray);
PolicyDocument = System.Convert.ToBase64String(ByteArray);
ByteArray = System.Text.Encoding.UTF8.GetBytes(AWSSecretAccessKey);
System.Security.Cryptography.HMACSHA1 MyHMACSHA1 = new System.Security.Cryptography.HMACSHA1(ByteArray);
ByteArray = System.Text.Encoding.UTF8.GetBytes(PolicyDocument);
Byte[] HashArray;
HashArray = MyHMACSHA1.ComputeHash(ByteArray);
PolicyDocumentSignature = System.Convert.ToBase64String(HashArray);
BindGridview();
//Uncomment the following lines if you would like to check if a CORS configuration exists and apply
//one if it does not exist.
if (GetBucketCorsExists() == false)
{
SetBucketCors();
}
/* System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(decimal));
for (int i = 1; i < 8; i++)
{
System.Data.DataRow row = table.NewRow();
row["ID"] = i;
row["Name"] = "Name " + i;
row["Salary"] = 10000 * i;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
*/
}
else
{ Response.Redirect("Default.aspx"); }
}
}
private static Boolean GetBucketCorsExists()
{
String RequestURL;
String RequestMethod;
System.Collections.Generic.Dictionary<String, String> ExtraRequestHeaders;
String AuthorizationValue;
SprightlySoftAWS.REST MyREST = new SprightlySoftAWS.REST();
Boolean RetBool;
String PostData;
int ErrorNumber = 0;
String ErrorDescription = "";
String LogData = "";
System.Collections.Generic.Dictionary<String, String> FullRequestHeaders = new System.Collections.Generic.Dictionary<String, String>();
int ResponseStatusCode = 0;
String ResponseStatusDescription = "";
System.Collections.Generic.Dictionary<String, String> FullResponseHeaders = new System.Collections.Generic.Dictionary<String, String>();
String ResponseString = "";
RequestURL = MyREST.BuildS3RequestURL(true, "s3.amazonaws.com", BucketName, "", "?cors");
RequestMethod = "GET";
PostData = "";
ExtraRequestHeaders = new System.Collections.Generic.Dictionary<String, String>();
ExtraRequestHeaders.Add("x-amz-date", DateTime.UtcNow.ToString("r"));
AuthorizationValue = MyREST.GetS3AuthorizationValue(RequestURL, RequestMethod, ExtraRequestHeaders, AWSAccessKeyID, AWSSecretAccessKey);
ExtraRequestHeaders.Add("Authorization", AuthorizationValue);
RetBool = MakeAWSRequest(RequestURL, RequestMethod, ExtraRequestHeaders, PostData, ref ErrorNumber, ref ErrorDescription, ref LogData, ref FullRequestHeaders, ref ResponseStatusCode, ref ResponseStatusDescription, ref FullResponseHeaders, ref ResponseString);
if (ResponseStatusCode == 404)
{
return false;
}
else if (RetBool == true)
{
return true;
}
else
{
throw new Exception(LogData);
}
}
private static void SetBucketCors()
{
String RequestURL;
String RequestMethod;
System.Collections.Generic.Dictionary<String, String> ExtraRequestHeaders;
String AuthorizationValue;
SprightlySoftAWS.REST MyREST = new SprightlySoftAWS.REST();
Boolean RetBool;
String PostData;
int ErrorNumber = 0;
String ErrorDescription = "";
String LogData = "";
System.Collections.Generic.Dictionary<String, String> FullRequestHeaders = new System.Collections.Generic.Dictionary<String, String>();
int ResponseStatusCode = 0;
String ResponseStatusDescription = "";
System.Collections.Generic.Dictionary<String, String> FullResponseHeaders = new System.Collections.Generic.Dictionary<String, String>();
String ResponseString = "";
PostData = "";
PostData += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
PostData += "<CORSConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">";
PostData += "<CORSRule>";
PostData += "<AllowedOrigin>*</AllowedOrigin>";
PostData += "<AllowedMethod>PUT</AllowedMethod>";
PostData += "<AllowedMethod>POST</AllowedMethod>";
PostData += "<AllowedMethod>GET</AllowedMethod>";
PostData += "<AllowedMethod>HEAD</AllowedMethod>";
PostData += "<MaxAgeSeconds>3000</MaxAgeSeconds>";
PostData += "<AllowedHeader>*</AllowedHeader>";
PostData += "</CORSRule>";
PostData += "</CORSConfiguration>";
RequestURL = MyREST.BuildS3RequestURL(true, "s3.amazonaws.com", BucketName, "", "?cors");
RequestMethod = "PUT";
ExtraRequestHeaders = new System.Collections.Generic.Dictionary<String, String>();
SprightlySoftAWS.S3.CalculateHash MyCalculateHash = new SprightlySoftAWS.S3.CalculateHash();
String MyMD5;
MyMD5 = MyCalculateHash.CalculateMD5FromString(PostData);
ExtraRequestHeaders.Add("Content-MD5", MyMD5);
ExtraRequestHeaders.Add("x-amz-date", DateTime.UtcNow.ToString("r"));
AuthorizationValue = MyREST.GetS3AuthorizationValue(RequestURL, RequestMethod, ExtraRequestHeaders, AWSAccessKeyID, AWSSecretAccessKey);
ExtraRequestHeaders.Add("Authorization", AuthorizationValue);
RetBool = MakeAWSRequest(RequestURL, RequestMethod, ExtraRequestHeaders, PostData, ref ErrorNumber, ref ErrorDescription, ref LogData, ref FullRequestHeaders, ref ResponseStatusCode, ref ResponseStatusDescription, ref FullResponseHeaders, ref ResponseString);
if (RetBool == false)
{
throw new Exception(LogData);
}
}
private static Boolean MakeAWSRequest(String RequestURL, String RequestMethod, System.Collections.Generic.Dictionary<String, String> UserRequestHeaders, String PostData, ref int ErrorNumber, ref String ErrorDescription, ref String LogData, ref System.Collections.Generic.Dictionary<String, String> FullRequestHeaders, ref int ResponseStatusCode, ref String ResponseStatusDescription, ref System.Collections.Generic.Dictionary<String, String> FullResponseHeaders, ref String ResponseStringFormatted)
{
SprightlySoftAWS.REST MyREST = new SprightlySoftAWS.REST();
Boolean RetBool = true;
LogData = "";
int AWSErrorRetries = 5;
for (int i = 0; i <= AWSErrorRetries; i++)
{
LogData += Environment.NewLine;
LogData += "-Request Started " + DateTime.Now.ToString() + Environment.NewLine;
LogData += "-RequestURL=" + RequestURL + Environment.NewLine;
LogData += "-RequestMethod=" + RequestMethod + Environment.NewLine;
if (UserRequestHeaders != null)
{
foreach (System.Collections.Generic.KeyValuePair<String, String> MyKeyValuePair in UserRequestHeaders)
{
LogData += "-RequestHeader=" + MyKeyValuePair.Key + ":" + MyKeyValuePair.Value + Environment.NewLine;
}
}
LogData += "-RequestPostData=" + PostData + Environment.NewLine;
RetBool = MyREST.MakeRequest(RequestURL, RequestMethod, UserRequestHeaders, PostData);
LogData += "-Request Complete " + DateTime.Now.ToString() + Environment.NewLine;
LogData += "-ResponseErrorNumber=" + MyREST.ErrorNumber + Environment.NewLine;
LogData += "-ResponseErrorDescription=" + MyREST.ErrorDescription + Environment.NewLine;
LogData += "-ResponseStatusCode=" + MyREST.ResponseStatusCode + Environment.NewLine;
LogData += "-ResponseStatusDescription=" + MyREST.ResponseStatusDescription + Environment.NewLine;
if (MyREST.ResponseHeaders != null)
{
foreach (System.Collections.Generic.KeyValuePair<String, String> MyKeyValuePair in MyREST.ResponseHeaders)
{
LogData += "-ResponseHeader=" + MyKeyValuePair.Key + ":" + MyKeyValuePair.Value + Environment.NewLine;
}
}
LogData += "-ResponseString=" + MyREST.ResponseString + Environment.NewLine;
//Set the return values.
ErrorNumber = MyREST.ErrorNumber;
ErrorDescription = MyREST.ErrorDescription;
FullRequestHeaders = MyREST.RequestHeaders;
ResponseStatusCode = MyREST.ResponseStatusCode;
ResponseStatusDescription = MyREST.ResponseStatusDescription;
FullResponseHeaders = MyREST.ResponseHeaders;
ResponseStringFormatted = MyREST.ResponseStringFormatted;
if (RetBool == true)
{
break;
}
else
{
if (MyREST.ResponseStatusCode == 500 || MyREST.ResponseStatusCode == 503)
{
//A Service Unavailable response was returned. Wait and retry.
System.Threading.Thread.Sleep(1000 * i * i);
}
else if (MyREST.ResponseStatusCode == 0 && MyREST.ErrorNumber == 1003)
{
//Getting the response failed. This may be a network disconnection. Wait and retry.
System.Threading.Thread.Sleep(1000 * i * i);
}
else
{
//An error occured but retrying would not solve the problem.
break;
}
}
}
return RetBool;
}