Java 使用原始文件名下载文件
在我的项目中,我上传了一个文件。上载时,我将其原始文件名和扩展名保存在数据库中,并使用服务器上的一些Java 使用原始文件名下载文件,java,spring-mvc,Java,Spring Mvc,在我的项目中,我上传了一个文件。上载时,我将其原始文件名和扩展名保存在数据库中,并使用服务器上的一些GUID保存该文件,生成的GUID也与文件名和扩展名一起存储在数据库中 例如— -用于上载的文件名为questions.docx -那么原始文件名将是“问题” -文件扩展名为“.docx” -上传文件,文件名为“0c1b96d3-af54-40d1-814d-b863b7528b1c” 上传工作正常。但当我下载某个文件时,它会以文件名作为GUID下载,在上面的例子中是“0c1b96d3-af54-
GUID
保存该文件,生成的GUID也与文件名和扩展名一起存储在数据库中
例如—
-用于上载的文件名为questions.docx
-那么原始文件名将是“问题”
-文件扩展名为“.docx”
-上传文件,文件名为“0c1b96d3-af54-40d1-814d-b863b7528b1c”
上传工作正常。但当我下载某个文件时,它会以文件名作为GUID下载,在上面的例子中是“0c1b96d3-af54-40d1-814d-b863b7528b1c”。如何下载具有原始文件名的文件,即“questions.docx” 添加的代码
/**
* code to display files on browser
*/
File file = null;
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
/**
* C://DocumentLibrary// path of evidence library
*/
String fileName = URLEncoder.encode(fileRepo.getRname(), "UTF-8");
fileName = URLDecoder.decode(fileName, "ISO8859_1");
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment; filename="+ fileName);
String newfilepath = "C://DocumentLibrary//" + systemFileName;
file = new File(newfilepath);
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
int readNum;
byte[] buf = new byte[1024];
try {
for (; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
} catch (IOException ex) {
}
ServletOutputStream out = response.getOutputStream();
bos.writeTo(out);
} catch (Exception e) {
// TODO: handle exception
} finally {
if (file != null) {
file = null;
}
if (fis != null) {
fis.close();
}
if (bos.size() <= 0) {
bos.flush();
bos.close();
}
}
/**
*在浏览器上显示文件的代码
*/
File=null;
FileInputStream fis=null;
ByteArrayOutputStream bos=null;
试一试{
/**
*C://DocumentLibrary//证据库路径
*/
String fileName=URLEncoder.encode(fileRepo.getRname(),“UTF-8”);
fileName=urldecker.decode(文件名为“ISO8859_1”);
response.setContentType(“应用程序/x-msdownload”);
response.setHeader(“内容处置”、“附件;文件名=“+filename”);
字符串newfilepath=“C://DocumentLibrary/”+systemFileName;
文件=新文件(newfilepath);
fis=新文件输入流(文件);
bos=新的ByteArrayOutputStream();
int readNum;
字节[]buf=新字节[1024];
试一试{
对于(;(readNum=fis.read(buf))!=-1;){
bos.write(buf,0,readNum);
}
}捕获(IOEX异常){
}
ServletOutputStream out=response.getOutputStream();
bos.writeTo(out);
}捕获(例外e){
//TODO:处理异常
}最后{
如果(文件!=null){
file=null;
}
如果(fis!=null){
fis.close();
}
如果(bos.size(),则可以在标题中设置文件名
例如,假设您正在使用RestFul Webservice,则可以这样使用:
ResponseBuilder rsp = Response.ok("Your Content Here", "application/docx");
rsp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
内容类型和文件名都可以在运行时设置。您只需从数据库中获取原始名称,并在内容处置
标题中设置即可:
@RequestMapping("/../download")
public ... download(..., HttpServletResponse response) {
...
response.setHeader("Content-Disposition", "attachment; filename=\"" + original + "\"");
}
您应该将原始文件名设置到响应头中,如下所示:
String fileName = URLEncoder.encode(tchCeResource.getRname(), "UTF-8");
fileName = URLDecoder.decode(fileName, "ISO8859_1");
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment; filename="+ fileName);
希望能帮助你:)你好@a请使用下面的代码
response.setHeader("Content-Disposition", "attachment; filename="+FILENAME+".docx");
要在响应头中使用当前日期命名文件,可以使用以下代码:
final String Date_FORMAT = "dd/MM/yyyy";
Date currentDate = new Date();
SimpleDateFormat formatDate = new SimpleDateFormat(Date_FORMAT);
String datenew = formatDate.format(currentDate);
response.setContentType("application/pdf");//for pdf file
response.setHeader("Content-disposition","attachment;filename="+ datenew +"Smoelenboek.pdf");
日期\格式可以是您想要的任何日期格式!!:)
根据
此代码可以处理非ASCII字符。部分代码是从Spring Framework复制的
import java.nio.charset.Charset;
import org.springframework.http.HttpHeaders;
import org.springframework.util.Assert;
public class HttpHeadersExtended extends HttpHeaders {
public static final String CONTENT_DISPOSITION_INLINE = "inline";
public static final String CONTENT_DISPOSITION_ATTACHMENT = "attachment";
/**
* Set the (new) value of the {@code Content-Disposition} header
* for {@code main body}, optionally encoding the filename using the RFC 5987.
* <p>Only the US-ASCII, UTF-8 and ISO-8859-1 charsets are supported.
*
* @param type content disposition type
* @param filename the filename (may be {@code null})
* @param charset the charset used for the filename (may be {@code null})
* @see <a href="https://tools.ietf.org/html/rfc7230#section-3.2.4">RFC 7230 Section 3.2.4</a>
* @since 4.3.3
*/
public void setContentDisposition(String type, String filename, Charset charset) {
if (!CONTENT_DISPOSITION_INLINE.equals(type) && !CONTENT_DISPOSITION_ATTACHMENT.equals(type)) {
throw new IllegalArgumentException("type must be inline or attachment");
}
StringBuilder builder = new StringBuilder(type);
if (filename != null) {
builder.append("; ");
if (charset == null || charset.name().equals("US-ASCII")) {
builder.append("filename=\"");
builder.append(filename).append('\"');
} else {
builder.append("filename*=");
builder.append(encodeHeaderFieldParam(filename, charset));
}
}
set(CONTENT_DISPOSITION, builder.toString());
}
/**
* Copied from Spring {@link org.springframework.http.HttpHeaders}
*
* Encode the given header field param as describe in RFC 5987.
*
* @param input the header field param
* @param charset the charset of the header field param string
* @return the encoded header field param
* @see <a href="https://tools.ietf.org/html/rfc5987">RFC 5987</a>
*/
private static String encodeHeaderFieldParam(String input, Charset charset) {
Assert.notNull(input, "Input String should not be null");
Assert.notNull(charset, "Charset should not be null");
if (charset.name().equals("US-ASCII")) {
return input;
}
Assert.isTrue(charset.name().equals("UTF-8") || charset.name().equals("ISO-8859-1"),
"Charset should be UTF-8 or ISO-8859-1");
byte[] source = input.getBytes(charset);
int len = source.length;
StringBuilder sb = new StringBuilder(len << 1);
sb.append(charset.name());
sb.append("''");
for (byte b : source) {
if (isRFC5987AttrChar(b)) {
sb.append((char) b);
} else {
sb.append('%');
char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16));
char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
sb.append(hex1);
sb.append(hex2);
}
}
return sb.toString();
}
/**
* Copied from Spring {@link org.springframework.http.HttpHeaders}
*/
private static boolean isRFC5987AttrChar(byte c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
c == '!' || c == '#' || c == '$' || c == '&' || c == '+' || c == '-' ||
c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
}
}
import java.nio.charset.charset;
导入org.springframework.http.HttpHeaders;
导入org.springframework.util.Assert;
公共类HttpHeadersExtended扩展HttpHeaders{
公共静态最终字符串内容\u处置\u INLINE=“INLINE”;
公共静态最终字符串内容\u处置\u ATTACHMENT=“ATTACHMENT”;
/**
*设置{@code Content Disposition}头的(新)值
*对于{@code main body},可以选择使用RFC 5987对文件名进行编码。
*仅支持US-ASCII、UTF-8和ISO-8859-1字符集。
*
*@param-type内容处置类型
*@param filename文件名(可能是{@code null})
*@param charset用于文件名的字符集(可能是{@code null})
*@见
*@自4.3.3起
*/
public void setContentDisposition(字符串类型、字符串文件名、字符集字符集){
如果(!CONTENT_DISPOSITION_INLINE.equals(type)&&!CONTENT_DISPOSITION_ATTACHMENT.equals(type)){
抛出新的IllegalArgumentException(“类型必须是内联的或附件”);
}
StringBuilder=新的StringBuilder(类型);
如果(文件名!=null){
生成器。追加(“;”);
if(charset==null | | charset.name().equals(“US-ASCII”)){
append(“文件名=\”);
append(文件名).append(“\”);
}否则{
追加(“文件名*=”);
append(encodeHeaderFieldParam(文件名,字符集));
}
}
set(CONTENT_DISPOSITION,builder.toString());
}
/**
*复制自Spring{@link org.springframework.http.HttpHeaders}
*
*按照RFC 5987中的描述对给定的头字段参数进行编码。
*
*@param输入标题字段param
*@param charset头字段param string的字符集
*@返回编码的头字段参数
*@见
*/
私有静态字符串编码器HeaderFieldParam(字符串输入,字符集字符集){
notNull(输入,“输入字符串不应为null”);
notNull(字符集,“字符集不应为null”);
if(charset.name().equals(“US-ASCII”)){
返回输入;
}
Assert.isTrue(charset.name().equals(“UTF-8”)| | charset.name().equals(“ISO-8859-1”),
“字符集应为UTF-8或ISO-8859-1”);
byte[]source=input.getBytes(字符集);
int len=source.length;
StringBuilder sb=新的StringBuilder(len>4)和0xF,16);
char hex2=Character.toUpperCase(Character.forDigit(b&0xF,16));
某人附加(hex1);
某人附加(hex2);
}
}
使某人返回字符串();
}
/**
*复制自Spring{@link org.springframework.http.HttpHeaders}
*/
专用静态布尔值ISRFC5987ATRCHAR(字节c){
return(c>='0'&&c='a'&&c='a'&&c头中有这一行,您可以设置文件名:
response.setHeader("Content-disposition", "attachment; filename="+ fileName);
您还可以使用ContentDispositionBuilder添加到HttpHeaders实例
示例代码
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDisposition(
ContentDisposition.builder("attachment")
.filename(file.getName()).build());
return ResponseEntity.ok()
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.headers(httpHeaders)
.body(resource);
什么是Res
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDisposition(
ContentDisposition.builder("attachment")
.filename(file.getName()).build());
return ResponseEntity.ok()
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.headers(httpHeaders)
.body(resource);