asp.net - File upload/download failing -


i'm working on website need have upload/download functionality. upload works fine, when press download uploaded file nothing happens.

//upload protected void btnupload_click(object sender, eventargs e)         {             string filename = path.getfilename(fileupload1.postedfile.filename);             fileupload1.saveas(server.mappath("files/" + filename));             con.open();             sqlcommand cmd = new sqlcommand("insert filestable(filename,filepath) values(@name,@path)", con);             cmd.parameters.addwithvalue("@name", filename);             cmd.parameters.addwithvalue("@path", "files/" + filename);             cmd.executenonquery();             con.close();             bindgridviewdata();         } //download  protected void gvdetails_selectedindexchanged(object sender, eventargs e)         {             sqlcommand com = new sqlcommand("select filename,filepath filestable id=@id", con);             com.parameters.addwithvalue("id", gvdetails.selectedrow.cells[1].text);             sqldatareader dr = com.executereader();              if (dr.read())             {                 response.clear();                 response.buffer = true;                  response.contenttype = dr["type"].tostring();                 response.addheader("content-disposition", "attachment;filename=" + dr["name"].tostring());                 response.charset = "";                 response.cache.setcacheability(httpcacheability.nocache);                 response.binarywrite((byte[])dr["data"]);                 response.end();             } } 

there few problems code:

  1. your select query returns filename , filepath try retrieve type , data database. can add column in table store file type since code saves uploaded file in files folder can use dr["type"]

  2. you need use same file path downloading used saving, either store absolute path or relative path in database:

    // uploading string filepath = server.mappath("files/" + filename); // absolute path or  string filepath = "files/" + filename; // relative path ... cmd.parameters.addwithvalue("@path", filepath);  // downloading string filepath = dr["filepath"]; // absolute path or string filepath = server.mappath(dr["filepath"]); // relative path 
  3. if file gets saved in folder instead of database read contents bytes sending client using file or filestream etc:

    // readallbytes throws memory exception large files byte[] filedata = file.readallbytes(filepath);  
  4. the select list contains filename column name , not name, replace dr["name"] dr["filename"]


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -