我正在尝试将附件保存在 ravenDb 中。我收到找不到文件的错误消息。
MVC View :
<input type="file" name="file" id="Ids2" style="float:right"/>
通过 ajax 调用,我将在上述控件中选择的文件名的值传递给 Controller 方法 - 该方法又将文件名发送给名为“上传”的自定义方法
public virtual string Upload(string fileName)
{
IDocumentSession session = GetCurrentDocumentSession();
var id = "upload/" + randomGen();
session.Advanced.DatabaseCommands.PutAttachment(id,null,
File.ReadAllBytes(fileName), optionalMetaData);
return id;
}
我得到 C:\ProgramFiles (x86)....没有指定的文件。 让我们在 View 中说 - 我浏览到 C:/Doc1.txt 并单击添加按钮,该按钮在 View 中保存了一堆其他字段,并且还从文件上传控件中获取了文件名/路径。
我在 session.advance.databasecommands... 行出现错误
Could not find file 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\Doc1.txt'.
如果我手动将 Doc1.txt 文件移动到上述位置,ravenDB 会保存附件,我可以从 localhost:8080/static/upload/keyvalue 中看到它
我怎样才能让 ravenDB 从用户选择的位置获取文件,而不是从 c:programfiles 的默认位置获取文件......
编辑:
function () {
var iFile = iContainer.find( '#Ids2' ).val();
var DataToSave = {
'Attachment' : iFile
};
var encodedData = $.toJSON(DataToSave);
$.ajax({
type: 'POST' ,
url: '/AttController/Attach' ,
data: encodedData,
contentType: 'application/json; charset=utf-8' ,
success: function (rc) {
if (rc.Success) {
// more javascript reroutes..business logic
}
else {
alert(rc.Message);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert( 'Error attaching \n' + xhr.response);
}
});
};
最佳答案
取决于浏览器 html 文件控件不存储文件的完整路径。如果你使用 Chrome 并调试脚本
var iFile = iContainer.find( '#Ids2' ).val();
将返回类似 C:\fakepath\yourfile.txt 的内容。与 IE 一样,返回完整路径。
此外,在 Ajax 中,您不是在推送文件的字节,而只是在推送文件名,这意味着除非您只在网络服务器上的浏览器中运行该网站,否则文件与网络服务器很 slim 。
如果您尝试通过 ajax 将文件上传到 MVC Controller ,我建议您使用 uploadify。
$("#Ids2").uploadify(
{
uploader: '/AttController/Attach',
swf: 'your/path/to/uploadify.swf',
cancelImg: 'your/path/to/cancel.jpg',
buttonText: 'Select File',
fileSizeLimit: '300KB',
fileTypeDesc: 'Image Files',
fileTypeExts: '*.gif; *.jpg; *.png',
auto: 'true',
multiple: 'false',
onError: function(type, info) {
},
onUploadSuccess: function(file, data, response) {
}
});
然后只需将您的 Controller 操作更改为
public virtual ActionResult Upload(HttpPostedFileBase FileData)
FileData 将包含 FileName 之类的内容,并且还将文件包含在输入流中。
关于html - ravendb上传文件报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11565951/