一、从请求头中content-disposition获取文件名
从请求头获取文件名代码:
//从请求头的content-disposition中获取filename
public String getFileName(HttpServletRequest request) throws ServletException, IOException {
String filename = null;
Collection<Part> parts = request.getParts();
for (Part part : parts) {
String headerValue = part.getHeader("content-disposition");
logger.error("headerValue:" + headerValue);
System.out.println("headerValue:" + headerValue);
String[] contentDisposition = headerValue != null ? headerValue.split(";") : new String[]{};
for (String value : contentDisposition) {
if (value.trim().startsWith("filename")) {
filename = value.substring(value.indexOf('=') + 1).trim().replace("\"", "");
return filename;
}
}
}
return filename;
}
二、请求头中没有content-disposition时获取文件名
下面这种情况,因为Content-Disposition标头出现在 HTTP POST 正文中,使用上面的代码无法从请求头获取到文件名,因此需要单独处理它们
这种情况可以使用commons-fileupload来解析
maven如下:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
获取文代名代码如下:
//从content-disposition中获取filename
public String getFileName(HttpServletRequest request) {
if (ServletFileUpload.isMultipartContent(request)) {//判断是否为多段数据
FileItemFactory firlfact = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(firlfact);
try {
List<FileItem> list = sfu.parseRequest(request);
for (FileItem fileItem : list) {
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String fileName = diskFileItem.getName();
if (fileName != null) {
return fileName;
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
参考:
How can I read the content of the content-disposition header
解决ServletFileUpload上传文件时,获取上传文件名出现中文乱码问题
Content-Disposition