ASP. NET rename a file when it is downloaded
- 2020-06-12 08:47:43
- OfStack
In some cases, to ensure that the file will not overwrite the previously uploaded files, and since there may be many files in the target directory, it is not a good idea to look them up one by one, so GUID can be generated automatically and the file name can be renamed to the original name of GUID_. However, it is probably best to ensure that the original name is restored when downloading. Listen to me this time. After searching 1 related data, we know that response can be used to solve the problem. The code is as follows.
[csharp]
< /pre > < br >
< br >
< pre > < /pre >
< p > < /p >
< pre > < /pre >
< p > < /p >
< pre > < /pre >
[csharp]
<pre name="code" class="csharp">string path = Server.MapPath("aa\\ahaakladahsasdas_bb.zip");
string newfileName = "";
if (File.Exists(path))
{
FileInfo fi = new FileInfo(path);
Response.Clear();//Clear Method deletes all of the buffers HTML The output. but Clear Method only deletes the response body
// Without deleting the response header. You can use this method to handle error cases.
Response.ClearHeaders();
Response.Buffer = false;// Indicates whether the output page is buffered when the property value is True When,
// The server will not send any information to the client until all the programs are executed or encountered
//Response.Flush or Response.End Statement will release the buffer information.
string filename = Path.GetFileName(path);
newfileName = newfileName + filename.Substring(filename.LastIndexOf("."));
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
newfileName = HttpUtility.UrlEncode(newfileName);// this 1 Step pop-up download saved dialog box, the filename appears disorderly, but the filename in the variable is normal.
Response.AppendHeader("Content-Disposition", "attachment;filename=" + newfileName);// Save the file for the user is the name of the display
// Tell the client the type of the response content is attachment You are through Response.AppendHeader("content-type", "attachment"); The statement.
Response.AppendHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(newfileName);// with response To return the path to the file
Response.Flush();// empty response
Response.End();
//Response.End(); Can be used if an exception is thrown
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
else
{
Response.Write("<script langauge=javascript>alert( 'The file does not exist !');</script>");
}
< /pre > < br >
< br >
< pre > < /pre >
< p > < /p >
< pre > < /pre >
< p > < /p >
< pre > < /pre >