Web part to download file with different name
-
31-12-2020 - |
Question
I would like to create a web part that will reside in the dispform.aspx in a document library. When the user presses a customized button it should be able to download the file but with a different name.
Does anyone has a sample code?
Solution
You can create your own ashx-handler in _layouts
folder. This handler will be responsible for starting download:
public class TestHandler: IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
//file itemId in document library
string itemId = context.Request.QueryString["itemId"];
//your document library guid
string listGuid = context.Request.QueryString["listGuid"];
byte[] fileContents = null;
using (SPSite site = new SPSite(SPContext.Current.Site.ID)
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID)
{
SPFile file = //here you get you file by listGuid and itemId
if (file.Exists)
{
fileContents = file.OpenBinary(SPOpenBinaryOptions.SkipVirusScan);
}
}
}
//name what you want
string fileName = "MY_NAME.Extention";
//starting downloading file
context.Response.Clear();
context.Response.ContentType = IMAGE_MIMETYPE;
context.Response.Headers["content-disposition"] = string.Format("attachment;filename={0}", fileName);
context.Response.BinaryWrite(fileContents);
}
}
After your handler is ready, you need to generate a link to your handler with file item id and list id (or list name), like "/_layouts/15/MyProject/TestHandler.ashx?fileId={0}&listGuid={1}"
.
When custom button pressed - you're following this link and downloads the file with your name.
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange