在这里我拿了这个,因为我正在发送给你,请看一次,请检查一次,这是做这项工作的正确方法
UploadController class file
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var uploadFolder = HostingEnvironment.MapPath("~/app_data");
uploadFolder = Path.Combine(uploadFolder, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
Directory.CreateDirectory(uploadFolder);
var streamProvider = new PreserveFilenameMultipartFileStreamProvider(uploadFolder);
var parts = await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (var uploadedFile in Directory.GetFiles(uploadFolder))
{
var thumbnail = Path.Combine(uploadFolder, "thumb-" + Path.GetFileName(uploadedFile));
var medium = Path.Combine(uploadFolder, "medium-" + Path.GetFileName(uploadedFile));
var large = Path.Combine(uploadFolder, "large-" + Path.GetFileName(uploadedFile));
ImageTools.Resize(uploadedFile, thumbnail, 100, 100);
ImageTools.Resize(uploadedFile, medium, 200, 200);
ImageTools.Resize(uploadedFile, large, 300, 300);
}
return Request.CreateResponse(HttpStatusCode.Accepted);
我在models文件夹中为imagetools制作了一个单独的文件
public class imageTools
{
public static void Resize(string original, string output, int width, int height)
{
using (var image = Image.FromFile(original))
using (var thumbnail = new Bitmap(width, height))
using (var graphics = Graphics.FromImage(thumbnail))
{
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.DrawImage(image, 0, 0, width, height);
ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
EncoderParameters encoderParameters;
encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
thumbnail.Save(output, info[1], encoderParameters);
}
}
}
我又拿了一个文件名
PreserveFilenameMultipartFileStreamProvider
public class PreserveFilenameMultipartFileStreamProvider : MultipartFileStreamProvider
{
public PreserveFilenameMultipartFileStreamProvider(string rootPath)
: base(rootPath)
{
}
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", "");
}
}
最后是我的布局页面
@using (Html.BeginRouteForm("DefaultApi", new { httproute = "", controller = "images" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="image" multiple="multiple" accept="image/*" />
<button type="submit">Upload</button>
}