我有一个视图模型,它有一个名为' StudentImage'的HttpPostedFileBase属性。当用户登录时,我想获取一个字节数组(我的数据来自DB)并显示它?我可以从数据库中获取byte [],我可以通过设置一个继承自httppostedfilebase的内存流将byte []设置回我的HttpPostedFileBase Image。但我的表格上没有出现任何图片
这是我的视图模型
public class EditStudentViewModel
{
...other code here
public HttpPostedFileBase StudentImage { get; set; }
}
这是我的控制器,我获取字节数组,我想将byte []设置为' StudentImage',这是一个HttpPostedFileBase
public ActionResult Edit()
{
var years = Enumerable.Range(DateTime.Now.Year - 100, 100).Reverse();
string userId = User.Identity.GetUserId();
Student student = studentRepository.Find(userId);
// student.StudentImage => this is a byte array that I need to get
// into the HttpPostedFileBase named StudentImage into
// 'EditStudentViewModel'
var studentViewModel = new EditStudentViewModel
{
...other properties set here
StudentImage = new MemoryFile(new MemoryStream(student.StudentImage.Image));
};
我创建了一个名为MemoryFile的新类,并像这样继承了HttpPostedBaseFIle
class MemoryFile : HttpPostedFileBase
{
Stream stream;
public MemoryFile(Stream stream)
{
this.stream = stream;
}
public override Stream InputStream
{
get { return stream; }
}
}
似乎正确设置了值,但是当我在屏幕上查看表单时,我看不到图像!它没有使用我在这里找到的Bootstrap文件插件来设置BootStrap File Upload Plugin
这是我的文件uplaod插件的javascript
$("#input-20").fileinput({
'type': 'POST',
'cache': false,
'browseClass': 'btn btn-primary btn-block',
'showCaption': false,
'showRemove': false,
'showUpload': false,
'uploadAsync': false,
'maxFileCount': 1,
'allowedFileExtensions': ['jpg', 'png', 'gif'],
'allowedFileTypes': ['image'],
//'uploadUrl': '@Url.Action("Edit", "Student")'
});
这是我的HTML标记
<div class="panel-body">
@Html.TextBoxFor(model => model.StudentImage, new { @type = "file", @id = "input-20" })
</div>
答案 0 :(得分:0)
您无法在<input type="file" />
中显示图片,必须使用<img>
标记。当你执行@Html.TextBoxFor(x => x, new { type="file" })
时,渲染的输出将是<input type="file" />
,没什么特别的。
如果您需要显示现有图像,您应该这样做:
<div class="panel-body">
<!-- show the current StudentImage in the database -->
<img src="@Url.Action("GetStudentImage", new { studentID= Model.StudentImageID })" />
<!-- for adding a new StudentImage -->
@Html.TextBoxFor(model => model.StudentImage, new { @type = "file", @id = "input-20" })
</div>
根据我在评论中发布的链接,您在控制器中的操作将如下所示:
public ActionResult GetStudentImage(int studentImageID)
{
Student student = studentRepository.Find(studentID);
return File(student.StudentImage.Image, "image/jpg");
}