原本之前使用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);
},