[英]Upload Image ASP.NET MVC
嘿,我想上传图片并将该图片保存到一个文件夹中,并将该图片的名称保存到数据库中,此外我还对表单的其他字段使用模型绑定。 这是此 HttpPostedFileBase 文件中的代码接收 null 我也在我的表单中使用 enctype = "multipart/form-data" 。
public ActionResult UmrahPackage(PackagesModel model, , HttpPostedFileBase file)
{
try
{
if (model.ID == 0)
{
String fileName = "";
Pakage pkg = new Pakage();
pkg.Title = model.Title;
pkg.PackageDetail = model.PackageDetail;
pkg.Duration = model.Duration;
if (file != null)
{
fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName);
string physicalPath = Server.MapPath("~/Images/Uploads" + fileName);
// save image in folder
file.SaveAs(physicalPath);
}}
另外我也在尝试这个,但我无法理解如何将图像保存在文件夹中我的意思是 SaveAs -> file 之前的对象实例
if (Request.Files.Count > 0 && String.IsNullOrEmpty(Request.Files[0].FileName) == false)
{
HttpPostedFileBase file;
fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(Request.Files[0].FileName);
string physicalPath = Server.MapPath("/uploads/profileimages/") + fileName;
file.SaveAs(physicalPath);
}
我的表格看起来像,
@using (Html.BeginForm("UmrahPackage", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
@Html.HiddenFor(model => model.ID)
<label>Title:</label>
@Html.TextBoxFor(model => model.Title)
<label>Upload Image</label>
<input type="file" id="imgInp">
<button type="submit" >Create</button>
}
请帮助我,谢谢。
您的输入元素name
属性值应与您的参数名称匹配
由于您的HttpPostedFileBase
参数名称是file
,请为您的文件输入提供相同的名称。
<input type="file" name="file" />
现在提交表单时,模型绑定器将能够将您提交的表单数据映射到您的参数命名file
我还建议您使用Path.Combine
而不是字符串连接。
string physicalPath = Path.Combine(Server.MapPath("~/Images/Uploads"), fileName);
我已经提到这个链接来解决覆盖以前选择的文件的问题。 但是这种方法导致了另一个问题。 选择的图片被复制。 这意味着如果我选择 3 张图片,它将保存 6 张。以下代码是我的 javascript
<input type="file" id="files" name="files" class="btn" style="color:white" multiple />
function previewImages() {
linebreak = document.createElement("br");
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
$('#files').val('');
return alert(file.name + " is not an image");
} else if (file.size > 4194304) {
$('#files').val('');
return alert(file.name + "is larger than 4MB");
} else {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.append(image.title);
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
}
//document.querySelector('#files').addEventListener("change", previewImages);
$(document).on('change', 'input[type="file"][multiple]', function () {
var $this = $(this);
$this.clone().insertAfter($this);
$this.hide();
});
$(document).on('change', 'input[type="file"][multiple]', previewImages);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.