如果您使用MVC,您可以嘗試下面的方法。它還使用按鈕上傳圖片:
型號:
[Display(Name = "Photo")]
public byte[] ImageData { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
查看:
<div>
@if (Model.ImageData == null)
{
<img id="myImage" class="photo" src="@Url.Content("~/Content/images/no_photo.png")" />
}
else
{
<img id="myImage" class="photo" src="@Url.Action("GetImage", "YourController", new { Model.ID })" />
}
<label for="myInput" class="custom-file-upload"></label>
<input type='file' id="myInput" name="image" />
</div>
<script>
//Preview & Update an image before it is uploaded
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#myImage').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#myInput").change(function() {
readURL(this);
});
</script>
的CSS:
/*For photo/image upload operations */
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid rgb(197, 197, 197);
border-radius: 4px 4px 4px 4px;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
float: right;
width: 5.25em;
margin-left:200px;
}
.photo{
width: 7em;
height: 9em;
border: 1px solid rgb(197, 197, 197);
border-radius: 4px 4px 4px 4px;
float:right;
}
<br/>
控制器:
public FileContentResult GetImage(int id)
{
var dataContext = repository.Participants.FirstOrDefault(p => p.ID == id);
if (dataContext != null)
{
return File(dataContext.ImageData, dataContext.ImageMimeType);
}
else
{
return null;
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Exclude = null)] Student student, HttpPostedFileBase image)
{
try
{
if (ModelState.IsValid)
{
if (image != null)
{
student.ImageMimeType = image.ContentType;
student.ImageData = new byte[image.ContentLength];
image.InputStream.Read(participant.ImageData, 0, image.ContentLength);
}
repository.SaveStudent(student);
………
請給我一個理由,爲什麼你給我否決? – zanhtet 2012-02-01 08:49:29