问题描述
嗨,我的代码有问题问题是上传,一切正常,但是当我必须从域上传图像时,它给了我这个错误,我尝试使用 .dispose();但它没有解决可能在错误的地方使用,Jpg,png 等。没有什么可以上传。请帮帮我..
还有一个问题,我不知道它是否与我的主要问题有关,当我尝试使用 Visual Studio Publish(FTP) 将我的项目上传到域时,它没有将我的 img 文件夹放在FTP,我必须从 FileZilla 手动创建
这是我做所有事情的代码
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FancyImageUploader.Models;
using System.Drawing;
using System.IO;
using System.Drawing.drawing2d;
using System.Net;
namespace FancyImageUploader.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/Index
public ActionResult Index()
{
var images = new ImagesModel();
//Read out files from the files directory
var files = Directory.GetFiles(Server.MapPath("~/Content/img/"));
//Add them to the model
foreach (var file in files)
images.Images.Add(Path.GetFileName(file));
return View(images);
}
//
// GET: /Home/UploadImage
public ActionResult UploadImage()
{
return View();
}
//
// POST: /Home/UploadImage
[HttpPost]
public ActionResult UploadImage(UploadImageModel model)
{
//Check if all simple data annotations are valid
if (ModelState.IsValid)
{
//Prepare the needed variables
Bitmap original = null;
var name = "newimagefile";
var errorField = string.Empty;
if (model.IsUrl)
{
errorField = "Url";
name = GetUrlFileName(model.Url);
original = GetimageFromUrl(model.Url);
}
else if (model.IsFlickr)
{
errorField = "Flickr";
name = GetUrlFileName(model.Flickr);
original = GetimageFromUrl(model.Flickr);
}
else if (model.File != null) // model.IsFile
{
errorField = "File";
name = Path.GetFileNameWithoutExtension(model.File.FileName);
original = Bitmap.FromStream(model.File.InputStream) as Bitmap;
}
//If we had success so far
if (original != null)
{
var img = CreateImage(original,model.X,model.Y,model.Width,model.Height);
//Demo purposes only - save image in the file system
var fn = Server.MapPath("~/Content/img/" + name + ".png");
img.Save(fn,System.Drawing.Imaging.ImageFormat.Png);
//Redirect to index
return RedirectToAction("Index");
}
else //Otherwise we add an error and return to the (prevIoUs) view with the model data
ModelState.AddModelError(errorField,"Your upload did not seem valid. Please try again using only correct images!");
}
return View(model);
}
/// <summary>
/// Gets an image from the specified URL.
/// </summary>
/// <param name="url">The URL containing an image.</param>
/// <returns>The
Bitmap GetimageFromUrl(string url)
{
var buffer = 1024;
Bitmap image = null;
if (!Uri.IsWellFormedUriString(url,UriKind.Absolute))
return image;
using (var ms = new MemoryStream())
{
var req = WebRequest.Create(url);
using (var resp = req.GetResponse())
{
using (var stream = resp.GetResponseStream())
{
var bytes = new byte[buffer];
var n = 0;
while ((n = stream.Read(bytes,buffer)) != 0)
ms.Write(bytes,n);
}
}
image = Bitmap.FromStream(ms) as Bitmap;
}
return image;
}
/// <summary>
/// Gets the filename that is placed under a certain URL.
/// </summary>
/// <param name="url">The URL which should be investigated for a file name.</param>
/// <returns>The file name.</returns>
string GetUrlFileName(string url)
{
var parts = url.Split(new char[] { '/' },StringSplitOptions.RemoveEmptyEntries);
var last = parts[parts.Length - 1];
return Path.GetFileNameWithoutExtension(last);
}
/// <summary>
/// Creates a small image out of a larger image.
/// </summary>
/// <param name="original">The original image which should be cropped (will remain untouched).</param>
/// <param name="x">The value where to start on the x axis.</param>
/// <param name="y">The value where to start on the y axis.</param>
/// <param name="width">The width of the final image.</param>
/// <param name="height">The height of the final image.</param>
/// <returns>The cropped image.</returns>
Bitmap CreateImage(Bitmap original,int x,int y,int width,int height)
{
var img = new Bitmap(width,height);
using (var g = Graphics.FromImage(img))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(original,new Rectangle(0,width,height),x,y,height,GraphicsUnit.Pixel);
}
return img;
}
}
}
这是我的 cshtml 与 HomeController 一起使用
@using Deneme.source
@model FancyImageUploader.Models.UploadImageModel
@{
ViewBag.Title = "Image uploader";
}
@section Styles
{
<link href="@Url.Content("~/Content/ImageArea.css")" rel="stylesheet" />
}
@section Scripts
{
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.imgareaselect.js")"></script>
<script>
$(document).ready(function () {
//Get the checkBoxes and disable them
var Boxes = $('input[type=checkBox]').attr('disabled',true);
//Get the preview image and set the onload event handler
var preview = $('#preview').load(function () {
setPreview();
ias.setoptions({
x1: 0,y1: 0,x2: $(this).width(),y2: $(this).height(),show: true
});
});
//Set the 4 coordinates for the cropping
var setPreview = function (x,w,h) {
$('#X').val(x || 0);
$('#Y').val(y || 0);
$('#Width').val(w || preview[0].naturalWidth);
$('#Height').val(h || preview[0].naturalHeight);
};
//Initialize the image area select plugin
var ias = preview.imgAreaSelect({
handles: true,instance: true,parent: 'body',onSelectEnd: function (s,e) {
var scale = preview[0].naturalWidth / preview.width();
var _f = Math.floor;
setPreview(_f(scale * e.x1),_f(scale * e.y1),_f(scale * e.width),_f(scale * e.height));
}
});
//Check one of the checkBoxes
var setBox = function (filter) {
$('button').attr('disabled',false);
Boxes.attr('checked',false)
.filter(filter).attr({ 'checked': true,'disabled': false });
};
//Initial state of X,Y,Width and Height is 0 0 1 1
setPreview(0,1,1);
//Fetch Flickr images
var fetchImages = function (query) {
$.getJSON('http://www.flickr.com/services/Feeds/photos_public.gne?jsoncallback=?',{
tags: query,tagmode: "any",format: "json"
},function (data) {
var screen = $('<div />').addClass('waitScreen').click(function () {
$(this).remove();
}).appendTo('body');
var Box = $('<div />').addClass('flickrImages').appendTo(screen);
$.each(data.items,function (i,v) {
console.log(data.items[i]);
$('<img />').addClass('flickrImage').attr('src',data.items[i].media.m).click(function () {
$('#Flickr').val(this.src).change();
screen.remove();
}).appendTo(Box);
});
});
};
//Flickr
$('#FlickrQuery').change(function () {
fetchImages(this.value);
});
$('#Flickr').change(function () {
setBox('#IsFlickr');
preview.attr('src',this.value);
});
//What happens if the URL changes?
$('#Url').change(function () {
setBox('#IsUrl');
preview.attr('src',this.value);
});
//What happens if the File changes?
$('#File').change(function (evt) {
var f = evt.target.files[0];
var reader = new FileReader();
if (!f.type.match('image.*')) {
alert("The selected file does not appear to be an image.");
return;
}
setBox('#IsFile');
reader.onload = function (e) { preview.attr('src',e.target.result); };
reader.readAsDataURL(f);
});
//What happens if any checkBox is checked ?!
Boxes.change(function () {
setBox(this);
$('#' + this.id.substr(2)).change();
});
$('button').attr('disabled',true);
$('form').submit(function () {
$('button').attr('disabled',true).text('Please wait ...');
});
});
</script>
}
<h2>Upload an image</h2>
@using (Html.BeginForm("UploadImage","Home",FormMethod.Post,new { enctype = "multipart/form-data" }))
{
@Html.HiddenFor(model => model.X)
@Html.HiddenFor(model => model.Y)
@Html.HiddenFor(model => model.Width)
@Html.HiddenFor(model => model.Height)
@Html.HiddenFor(model => model.Flickr)
<div id="upload-choices">
<div class="editor-row">
<div class="editor-label">
@Html.EditorFor(model => model.IsUrl)
@Html.LabelFor(model => model.Url)
</div><div class="editor-field">
@Html.EditorFor(model => model.Url)
@Html.ValidationMessageFor(model => model.Url)
</div>
</div>
<div class="editor-row">
<div class="editor-label">
@Html.EditorFor(model => model.IsFlickr)
@Html.LabelFor(model => model.Flickr)
</div><div class="editor-field">
@Html.Editor("FlickrQuery")
@Html.ValidationMessageFor(model => model.Flickr)
</div>
</div>
<div class="editor-row">
<div class="editor-label">
@Html.EditorFor(model => model.IsFile)
@Html.LabelFor(model => model.File)
</div><div class="editor-field">
@Html.FileFor(model => model.File)
@Html.ValidationMessageFor(model => model.File)
</div>
</div>
<div class="editor-row">
@Html.ValidationSummary(true)
</div>
</div>
<div id="upload-cut">
<img alt="Field for image cutting" id="preview" src="@Url.Content("~/Content/empty.png")" />
</div>
<div class="clear">
<button type="submit">Upload</button>
</div>
}
解决方法
我发现了 FTP 文件权限问题的问题,已修复。