Refine search
@MultipartConfig @WebServlet("/uploadServlet") public class UploadServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part file = request.getPart("file"); String filename = getFilename(file); InputStream filecontent = file.getInputStream(); // ... Do your file saving job here. response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write("File " + filename + " successfully uploaded"); 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;
private FlowFile savePartDetailsAsAttributes(final ProcessSession session, final Part part, final FlowFile flowFile, final int sequenceNumber, final int allPartsCount) {
final Map<String, String> attributes = new HashMap<>();
for (String headerName : part.getHeaderNames()) {
final String headerValue = part.getHeader(headerName);
putAttribute(attributes, "http.headers.multipart." + headerName, headerValue);
putAttribute(attributes, "http.multipart.size", part.getSize());
putAttribute(attributes, "http.multipart.content.type", part.getContentType());
putAttribute(attributes, "http.multipart.name", part.getName());
putAttribute(attributes, "http.multipart.filename", part.getSubmittedFileName());
putAttribute(attributes, "http.multipart.fragments.sequence.number", sequenceNumber + 1);
putAttribute(attributes, "http.multipart.fragments.total.number", allPartsCount);
return session.putAllAttributes(flowFile, attributes);
@Override public void cleanupMultipart(MultipartHttpServletRequest request) { if (!(request instanceof AbstractMultipartHttpServletRequest) || ((AbstractMultipartHttpServletRequest) request).isResolved()) { // To be on the safe side: explicitly delete the parts, // but only actual file parts (for Resin compatibility) try { for (Part part : request.getParts()) { if (request.getFile(part.getName()) != null) { part.delete(); catch (Throwable ex) { LogFactory.getLog(getClass()).warn("Failed to perform cleanup of multipart items", ex);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ... List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true"> for (Part filePart : fileParts) { String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix. InputStream fileContent = filePart.getInputStream(); // ... (do your job here)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String description = request.getParameter("description"); // Retrieves <input type="text" name="description"> Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file"> String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix. InputStream fileContent = filePart.getInputStream(); // ... (do your job here)
@Override public void transferTo(File dest) throws IOException, IllegalStateException { this.part.write(dest.getPath()); if (dest.isAbsolute() && !dest.exists()) { // Servlet 3.0 Part.write is not guaranteed to support absolute file paths: // may translate the given path to a relative location within a temp dir // (e.g. on Jetty whereas Tomcat and Undertow detect absolute paths). // At least we offloaded the file from memory storage; it'll get deleted // from the temp dir eventually in any case. And for our user's purposes, // we can manually copy it to the requested location as a fallback. FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest.toPath()));
throws ServletException, IOException {
final String path = request.getParameter("destination");
final Part filePart = request.getPart("file");
final String fileName = request.getParameter("filename");
final PrintWriter writer = response.getWriter();
out = new FileOutputStream(new File(path + File.separator
+ fileName));
fileContent = filePart.getInputStream();
while ((read = fileContent.read(bytes)) != -1) {
out.write(bytes, 0, read);
fileContent.close();
throws ServletException, IOException {
httpServletResponse.setContentType("text/html");
PrintWriter printWriter = httpServletResponse.getWriter();
for (Part part : httpServletRequest.getParts()) {
inputStream = httpServletRequest.getPart(part.getName()).getInputStream();
int i = inputStream.available();
byte[] b = new byte[i];
inputStream.read(b);
String fileName = "";
for (String temp : part.getHeader("content-disposition").split(";")) {
if (temp.trim().startsWith("filename")) {
fileName = temp.substring(temp.indexOf('=') + 1).trim().replace("\"", "");
fileOutputStream = new FileOutputStream(uploadDir + "/" + fileName);
fileOutputStream.write(b);
inputStream.close();
fileOutputStream.close();
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
final String path = request.getParameter("destination");
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
final PrintWriter writer = response.getWriter();
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
filecontent.close();
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
public static Map<String, byte[]> getPostMap(HttpServletRequest request) {
Map<String, byte[]> map = new HashMap<>();
Map<String, String[]> pm = request.getParameterMap();
if (pm != null && pm.size() > 0) {
for (Map.Entry<String, String[]> entry: pm.entrySet()) {
String[] v = entry.getValue();
if (v != null && v.length > 0) map.put(entry.getKey(), UTF8.getBytes(v[0]));
} else try {
final byte[] b = new byte[1024];
for (Part part: request.getParts()) {
String name = part.getName();
InputStream is = part.getInputStream();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
try {while ((c = is.read(b, 0, b.length)) > 0) {
baos.write(b, 0, c);
}} finally {is.close();}
map.put(name, baos.toByteArray());
} catch (IOException e) {
} catch (ServletException e) {
return map;
Part filePart = request.getPart("file"); String fileName = String.valueOf("fileName"); File file = new File("/the/path/" + fileName); OutStream outFile = new FileOutputStream(file); InputStream filecontent = filePart.getInputStream(); int read = 0; byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { outFile.write(bytes, 0, read);
Part part = // obtain part somehow.. String photoFileName = // build a file name somehow.. InputStream photoInputStream = part.getInputStream(); FileOutputStream photoOutputStream = new FileOutputStream(System.getProperty("com.mycompany.uploadPath") + File.separator + photoFileName); IOUtils.copy(photoInputStream, photoOutputStream); // close streams here...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part part = request.getPart("myImg"); BufferedReader br = new BufferedReader(new InputStreamReader(part.getInputStream(), Charset.forName("utf-8"))); String sImg = br.readLine(); sImg = sImg.substring("data:image/png;base64,".length()); byte[] bImg64 = sImg.getBytes(); byte[] bImg = Base64.decodeBase64(bImg64); // apache-commons-codec FileOutputStream fos = new FileOutputStream("img.png"); fos.write(bImg);
InputStream in = null;
try {
Part p = httpRequest.getPart(name);
if (p != null) {
long len = p.getSize();
if (len > MAX_STRING_SIZE)
throw new IOException("String too big: " + len);
in = p.getInputStream();
byte[] data = new byte[(int) len];
DataHelper.read(in, data);
String enc = httpRequest.getCharacterEncoding();
if (enc == null)
enc = "UTF-8";
throw ise;
} finally {
if (in != null) try { in.close(); } catch (IOException ioe) {}
String str = httpRequest.getParameter( name );
if( str != null )
result = str;
public void dumpPart(Part p) throws Exception { InputStream is = p.getInputStream(); if (!(is instanceof BufferedInputStream)) { is = new BufferedInputStream(is); int c; StringBuilder sb = new StringBuilder(); System.out.println("Message: "); while ((c = is.read()) != -1) { sb.append(c); String result= sb.toString(); sendmail.VerstuurEmail(mpMessage, kenmerk);
// The filename is passed as a URLencoded string String fileName = URLDecoder.decode(request.getParameter("fileName"), "UTF-8"); Path filePath = Paths.get(uploadFolder, fileName); Part filePart = request.getPart("file"); InputStream input = filePart.getInputStream(); try { Files.copy(input, filePath); } catch (Exception e) { log.error("Error writing file to disk: " + e.getMessage()); } finally { input.close();
private File savePartToTemp(Part part) {
File tempDir = Files.createTempDir();
try {
File uploadFile = new File(tempDir, part.getSubmittedFileName());
try (OutputStream uploadFileOut = new FileOutputStream(uploadFile)) {
IOUtils.copy(part.getInputStream(), uploadFileOut);
try {
ZipFile zipped = new ZipFile(uploadFile);
if (zipped.isValidZipFile()) {
zipped.extractAll(tempDir.getAbsolutePath());
} catch (Exception ex) {
throw new VisalloException("Could not expand zip file: " + uploadFile.getAbsolutePath(), ex);