C#應用 uploadify 上傳前判斷檔案是否存在
阿新 • • 發佈:2018-12-20
原本之前使用Guid.NewGuid().ToString() 產生隨機碼來命名上傳的檔案,不用擔心上傳的檔案重名而被覆蓋。現在新的需求是要要求檔案以原名儲存到伺服器,那麼就要預防上傳相同名稱的檔案,否則被覆蓋。以下就直接上程式碼:
1、檢視頁面的JS:
$(function () {
$('#file_upload').uploadify({
'buttonText': '請選擇上傳檔案', //設定上傳按鈕顯示文字
'fileTypeExts': '*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.htm;*.html;*.txt;*.zip;*.rar;*.gz;*.bz2;*.pdf;*.exe;*.jpg;*.bmp;*.jpeg;*.gif;*.png' , //設定允許上傳圖片格式描述,即允許上傳的檔案型別。
'sizeLimit': '51200', // 設定上傳大小,預設單位為KB。
//'queueSizeLimit': 1, //設定上傳佇列中同時允許的上傳檔案數量,預設為999
//'uploadLimit' : 1 //設定允許上傳的檔案數量,預設為999。
//單個檔案上傳完成時觸發事件
//'onUploadComplete': function (file) {
// alert('The file ' + file.name + ' finished processing.');
//},
//單個檔案上傳成功後觸發事件。
//上傳之前判斷檔案是否存在
'checkExisting': '/Sys/check_exists',
'onUploadSuccess': function (file, data, response) {
eval("data=" + data);
//alert('檔案 ' + file.name + ' 已經上傳成功,並返回 ' + response + ' 儲存檔名稱為 ' + data.SaveName);
saveAttachment(file.name, data.SaveName)
},
'swf': '@Url.Content("~/Scripts/uploadify-v3.1/uploadify.swf")',
'uploader': '/Sys/UploadAtt_originalName'
});
});
2、C#的check_exists action
[HttpPost]
public ActionResult check_exists(string filename = null)
{
if (filename == null)
{
return Content("null");
}
else
{
Int16 belongTo = 1;
var attList = db_reqAtt.sys_reqAttachments.Where(a => a.belongTo == belongTo).Where(a => a.attachment == filename).AsQueryable();
if (attList.Count() > 0)
{
return Content("1");
}
else
{
return Content("0");
}
}
}
3、jquery.uploadify.js關於onUploadStart有部分要修改的,修改如下:
onUploadStart : function(file) {
// Load the swfupload settings
var settings = this.settings;
var timer = new Date();
this.timer = timer.getTime();
this.bytesLoaded = 0;
if (this.queueData.uploadQueue.length == 0) {
this.queueData.uploadSize = file.size;
}
if (settings.checkExisting) {
$.ajax({
type : 'POST',
async : false,
url : settings.checkExisting,
data : {filename: file.name},
success : function(data) {
if(data == "null"){
alert("filename is null");
}
else if (data == 1) {
var overwrite = confirm('A file with the name "' + file.name + '" already exists on the server.\nWould you like to replace the existing file?');
if (!overwrite) {
$('#file_upload').uploadify('cancel', file.id);
//this.cancelUpload(file.id);
$('#' + file.id).remove();
if (this.queueData.uploadQueue.length > 0 && this.queueData.queueLength > 0) {
if (this.queueData.uploadQueue[0] == '*') {
this.startUpload();
} else {
this.startUpload(this.queueData.uploadQueue.shift());
}
}
}
}
}
});
}
// Call the user-defined event handler
if (settings.onUploadStart) settings.onUploadStart.call(this, file);
},