简体   繁体   English

使用合适的内容类型将图像上传到ASP.NET网站

[英]Uploading image to ASP.NET site with avalible content-type

I currently have a web service set up to upload and save a file (.png image) to my website using the following code: 我目前已经设置了网络服务,使用以下代码将文件(.png图像)上传并保存到我的网站:

[WebMethod]
public string SaveDocument(byte[] docbinaryarray, string docname)
{
    string strdocPath;
    string docDirPath = Server.MapPath("\\") + uploadDir;
    strdocPath = docDirPath + docname;
    if (!Directory.Exists(docDirPath))
        Directory.CreateDirectory(docDirPath);
    FileStream objfilestream = new FileStream(strdocPath, FileMode.Create, FileAccess.ReadWrite);
    objfilestream.Write(docbinaryarray, 0, docbinaryarray.Length);
    objfilestream.Close();
    return "http:\\\\example.com\\" + uploadDir + docname;    
}

This code works fine, however when I access the image via the url I am not getting a content type that matches the png file (image/png). 这段代码可以正常工作,但是当我通过url访问图像时,没有得到与png文件(image / png)匹配的内容类型。 Is it possible to associate the content type when you upload a file so that when you visit the url (example.com/myimage.png) it returns the image with the image/png content type? 上传文件时是否可以关联内容类型,以便在访问URL(example.com/myimage.png)时返回具有image / png内容类型的图像? Or do I need to somehow dynamically create webpages with the content type that link to these links? 还是我需要以某种方式动态创建具有链接到这些链接的内容类型的网页?

EDIT: The goal is to use this with a 3rd party API that needs to do a GET request and needs to know the content-type, right now it specifies as invalid. 编辑:目标是将其与需要执行GET请求并需要知道内容类型的第三方API一起使用,现在它指定为无效。

I think that something is not configired well in a your web server that blocks files or you pass wrong file name to this web service method. 我认为您的阻止文件的Web服务器中的配置不正确,或者您将错误的文件名传递给此Web服务方法。

I tested it and wrote simple implementation and all worked well. 我对其进行了测试并编写了简单的实现,并且一切正常。 ASP.NET page uploads image to web service, web service returns a URL to uploaded image, page displays the image through Image1 control. ASP.NET页面将图像上传到Web服务,Web服务返回URL到上传的图像,页面通过Image1控件显示图像。

My simple implementation: 我的简单实现:

Default.aspx: Default.aspx:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_OnClick" />
    <asp:Image ID="Image1" runat="server" />
    </form>
</body>
</html>

Default.aspx.cs: Default.aspx.cs:

namespace TestAspNetWebApp
{
    using System.IO;
    using System;

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_OnClick(object sender, EventArgs e)
        {
            string appPath = Request.PhysicalApplicationPath + "\\uploads\\";

            if (!Directory.Exists(appPath))
                Directory.CreateDirectory(appPath);

            if (FileUpload1.HasFile)
            {
                string savePath = appPath + Server.HtmlEncode(FileUpload1.FileName);
                FileUpload1.SaveAs(savePath);

                using (var objfilestream = new FileStream(savePath, FileMode.Open, FileAccess.Read))
                {
                    var len = (int) objfilestream.Length;
                    var mybytearray = new Byte[len];
                    objfilestream.Read(mybytearray, 0, len);

                    var myservice = new WebService();
                    var fileurl = myservice.SaveDocument(mybytearray, FileUpload1.FileName);
                    Image1.ImageUrl = fileurl;
                }

                File.Delete(savePath);
            }
        }
    }
}

WebService.asmx.cs: WebService.asmx.cs:

namespace TestAspNetWebApp
{
    using System.IO;
    using System.Web.Services;

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class WebService : System.Web.Services.WebService
    {
        private const string uploadDir = "uploads-websevice";

        [WebMethod]
        public string SaveDocument(byte[] docbinaryarray, string docname)
        {
            string strdocPath;

            string docDirPath = Server.MapPath("\\") + uploadDir + "\\";
            strdocPath = docDirPath + docname;

            if (!Directory.Exists(docDirPath))
                Directory.CreateDirectory(docDirPath);

            var objfilestream = new FileStream(strdocPath, FileMode.Create, FileAccess.ReadWrite);
            objfilestream.Write(docbinaryarray, 0, docbinaryarray.Length);
            objfilestream.Close();

            return "http://localhost:57064/" + uploadDir + "/" + docname;
        }
    }
}

Please add some example of your code to help you to define the problem and to solive it. 请添加一些代码示例,以帮助您定义问题并缓解问题。

It seems that server returns all headers and also 'Content-type' as usual. 似乎服务器照常返回所有标头以及“ Content-type”。

using (var client = new WebClient())
{
      string uri = "http://chronicletwilio.azurewebsites.net/res/12345.png";
      byte[] data = client.DownloadData(uri);
      string contentType = client.ResponseHeaders["content-type"];
      // contentType is 'image/png'
}

I figured out the problem. 我解决了这个问题。 Even though the content type header was set, the file was not being read as an image, but only as a file. 即使设置了内容类型标头,该文件也不会作为图像读取,而只是作为文件读取。 That being the case the 3rd party API I was using was not correctly reading it and complained about the content type. 在这种情况下,我使用的第3方API无法正确读取它并抱怨内容类型。 The fix ended up being chaning my method to the following: 该修复程序最终将我的方法更改为以下内容:

[WebMethod]
        public string SaveImage(byte[] docbinaryarray, string docname)
        {
            string strdocPath;
            string docDirPath = Server.MapPath("/") + uploadDir;
            strdocPath = docDirPath + docname;
            if (!Directory.Exists(docDirPath))
                Directory.CreateDirectory(docDirPath);
            using (Image image = Image.FromStream(new MemoryStream(docbinaryarray)))
            {
                image.Save(strdocPath, ImageFormat.Png);  // Or Png
            }
            return "http://example.com/" + uploadDir + docname;

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试使用Ajax将png上载到Asp.net Core服务器时出现“错误的Content-Type:image / png” - “Incorrect Content-Type: image/png” when trying to upload png with Ajax to Asp.net Core server InvalidOperationException:错误的内容类型:ASP.NET Core - InvalidOperationException: Incorrect Content-Type: ASP.NET Core ASP.NET MVC应用程序不输出内容类型标头 - ASP.NET MVC Application not outputting content-type header 在ASP.NET MVC中设置空响应的Content-Type - Setting the Content-Type of an empty response in ASP.NET MVC ASP.NET 异步处理程序内容类型未发送 - ASP.NET async handler content-type not sent ASP.Net SoapHttpClientProtocol中的HTTP内容类型 - HTTP Content-Type in ASP.Net SoapHttpClientProtocol 发送到ASP.NET Web API时,请求标头中Angular 5缺少Content-type - Angular 5 missing Content-type in request headers when send to ASP.NET Web API 如何从ASP.NET Core MVC响应的Content-Type中删除字符集? - How do I remove the charset from Content-Type in a ASP.NET Core MVC response? ASP.NET重写的自定义错误不会发送内容类型标头 - ASP.NET rewritten custom errors do not send content-type header 从 ASP.NET Core 中的 controller 返回 Content-Type 作为 application/javascript - Returning Content-Type as application/javascript from a controller in ASP.NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM