Reputation: 2917
In the following code:
public static MultipartEntity buildMultiEntity(final SlingHttpServletRequest request) {
MultipartEntity multipartEntity = null;
final Map<String, RequestParameter[]> params = request.getRequestParameterMap();
if(params.containsKey("myfile")) {
multipartEntity = new MultipartEntity();
for (final Map.Entry<String, RequestParameter[]> pairs : params.entrySet()) {
final String key = pairs.getKey();
final RequestParameter[] parameterArray = pairs.getValue();
final RequestParameter param = parameterArray[0];
InputStream inputStream = null;
try {
inputStream = param.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
multipartEntity.addPart(key, new InputStreamBody(inputStream, param.getFileName()));
}
}
return multipartEntity;
}
I identify if the request has image as follow
if(params.containsKey("myfile"))
How to identify, if the request has image even if I dont know, what is the input name of the image file?
Upvotes: 3
Views: 4607
Reputation: 223
I think you can try to use attachment for this purpose.
For this you need to add enctype="multipart/form-data"
in your form on UI.
It will be smth like
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
// some other inputs
</form>
And server side
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
// ...
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
InputStream fileContent = filePart.getInputStream();
// some job here
}
private static String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
Upvotes: 1