8

I'm uploading a blob file from an HTML form to a database using JSP. I need to insert the filename into DB. I know that the filename is stored in the Content-Disposition header, how could I get that?

bruno
  • 2,213
  • 1
  • 19
  • 31
h2c
  • 235
  • 1
  • 3
  • 11

1 Answers1

23

If you uploaded the file using JavaEE 6 with HttpServletRequest.getPart:

Part part = request.getPart("xxx"); // input type=file name=xxx
String disposition = part.getHeader("Content-Disposition");
String fileName = disposition.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1");

See Part.


As @Marc mentioned I did not treat URL encoding. (He also made the quotes around the filename optional.)

fileName = URLDecoder.decode(fileName, StandardCharsets.ISO_8859_1);

Not checked, but HTTP encoding for headers should be the default ISO-8859-1.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Thanks ! Just in case someone else tries this : it worked for me using Apache CXF rest controller and getting the "part" as an attachment from a MultipartBody object. – matthieusb Apr 03 '17 at 09:38
  • You'd also need to decode the filename as it's (URL?) encoded. – Marc Nov 03 '17 at 09:18
  • @Marc thanks, not tested in the wild, but I agree. I have put the blame on you. – Joop Eggen Nov 03 '17 at 09:26
  • The regex is pretty dangerous. I wanted to get the part `name` entry, so replaced your `filename` with `name`. Still got the `filename` param, as your regex accepts anything before `name=`. I think the only way to parse it is to literally iterate it char by char, understand whether you are inside a string or not (a file name could contain `filename=` substring and mislead you too) – SomethingSomething Dec 20 '17 at 13:58
  • This worked for me and I think is safer: 1. `String regex = "(?i)^.*; " + paramName + "=\"?([^\"]+)\"?.*$";` (`paramName` should be `name` of `filename` or whatever you want to get). Then 2. `return headerLine.replaceFirst(regex, "$1")`; – SomethingSomething Dec 20 '17 at 14:04
  • The only change is that I added `; ` after your `(?i)^.*` – SomethingSomething Dec 20 '17 at 14:05
  • Furthermore, I'd change `[^\"]+` to `[^\"]*`, as currently, the regex does not support empty values – SomethingSomething Dec 20 '17 at 14:19