简体   繁体   中英

File upload using multipart/form-data

I used this code to upload a file but its not uploading

var content = new MultipartFormDataContent();

var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filePath));

fileContent.Headers.ContentDisposition =
    new ContentDispositionHeaderValue("attachment")
    {
        FileName = Path.GetFileName(filePath)
    };

content.Add(fileContent);
var responce = client.PostAsync(queryString.ToString(), content).Result;

Try this

<form id="form1" runat="server">
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" /> <br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
</form>

protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
    try
    {
        string filename = Path.GetFileName(FileUploadControl.FileName);
        FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
        StatusLabel.Text = "Upload status: File uploaded!";
    }
    catch(Exception ex)
    {
        StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
    }
}
}

The status messages should clearly indicate what they are all about, and you can change them to fit your needs.

Try this code. Its working properly. Only you have to make a folder with name "Upload" in your solution explorer where files will be uploaded.

in your aspx page

<asp:FileUpload runat="server" ID="FileUploadContacts" Width="300px" />
<asp:Button runat="server" ID="btnUpload" Text="Upload" OnClick="btnUpload_OnClick" />

in code behind do this,

protected void btnUpload_OnClick(object sender, EventArgs e)
{
    try
    {
        if (FileUploadContacts.HasFile)
        {
            FileUploadContacts.SaveAs(Server.MapPath("Uploads//") + FileUploadContacts.FileName);
            this.lblMessage.Text = "File uploaded Successfully!>";
        }
        else
        {
            this.lblMessage.Text = "File not uploaded!>";
        }
    }
    catch (Exception ex)
    {
        Logger.WriteException(ex);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM