javaweb implementation file download method and instance code
- 2020-05-17 05:28:45
- OfStack
javaweb implementation file download
Stop using it < a > The tag is downloaded, and this will open the file instead of downloading it
Such as:
<
a href="E:\MyDesktop\37fecd65330184de67d419a8d02e7081.jpg"
>
download
<
/a
>
If I write this way, the browser will open the image directly, unless it's a file that a browser can't open
So we still need to use java itself for file reading and writing to download files
<
a href="downloadFile?filename=
<
s:property value='document_filename'/
>
"
>
download
<
/a
>
package com.cpsec.tang.chemical.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;
import com.cpsec.tang.chemical.biz.DocumentBiz;
import com.cpsec.tang.chemical.entity.Document;
import com.cpsec.tang.chemical.util.Pager;
import com.opensymphony.xwork2.ActionSupport;
@Controller("documentAction")
public class DocumentAction extends ActionSupport{private String filename;
public String downloadFile(){
System.out.println(filename);
try {
HttpServletResponse response=ServletActionContext.getResponse();
// Settings file MIME type
response.setContentType(ServletActionContext.getServletContext().getMimeType(filename));
// Set up the Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+filename);
// Gets the absolute path to the target file
String fullFileName = ServletActionContext.getServletContext().getRealPath("/files/" + filename);
//System.out.println(fullFileName);
// Read the file
InputStream in = new FileInputStream(fullFileName);
// Read the target file through response Write the target file to the client
OutputStream out = response.getOutputStream();
// Write files
int b;
while((b=in.read())!= -1)
{
out.write(b);
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
}
Thank you for reading, I hope to help you, thank you for your support of this site!