├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── Readme.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── src ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── filedemo │ │ │ ├── FileDemoApplication.java │ │ │ ├── controller │ │ │ └── FileController.java │ │ │ ├── exception │ │ │ ├── FileStorageException.java │ │ │ └── MyFileNotFoundException.java │ │ │ ├── extraction │ │ │ ├── ExtractPdfSignature.java │ │ │ └── TemplateMatching.java │ │ │ ├── payload │ │ │ └── UploadFileResponse.java │ │ │ ├── property │ │ │ └── FileStorageProperties.java │ │ │ └── service │ │ │ └── FileStorageService.java │ └── resources │ │ ├── application.properties │ │ └── static │ │ ├── css │ │ └── main.css │ │ ├── index.html │ │ ├── js │ │ └── main.js │ │ └── train │ │ ├── SAMPLE PDF.jpeg │ │ ├── SIG CARD - PR_1.jpeg │ │ ├── SIG-CARD.jpeg │ │ ├── form3_sig.jpeg │ │ ├── noimage.jpeg │ │ └── passport3_1.jpeg └── test │ └── java │ └── com │ └── example │ └── filedemo │ └── FileDemoApplicationTests.java └── train ├── SAMPLE PDF.jpeg ├── SIG CARD - PR_1.jpeg ├── SIG-CARD.jpeg ├── form3_sig.jpeg ├── noimage.jpeg └── passport3_1.jpeg /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ 25 | uploads 26 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | ## Spring Boot File Upload / Download Rest API Example 2 | 3 | **Tutorial**: [Uploading an Downloading files with Spring Boot](https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/) 4 | 5 | ## Steps to Setup 6 | 7 | **1. Clone the repository** 8 | 9 | ```bash 10 | git clone https://github.com/callicoder/spring-boot-file-upload-download-rest-api-example.git 11 | ``` 12 | 13 | **2. Run the app using maven** 14 | 15 | ```bash 16 | cd spring-boot-file-upload-download-rest-api-example 17 | mvn spring-boot:run 18 | ``` 19 | 20 | That's it! The application can be accessed at `http://localhost:8080`. 21 | 22 | You may also package the application in the form of a jar and then run the jar file like so - 23 | 24 | ```bash 25 | mvn clean package 26 | java -jar target/file-demo-0.0.1-SNAPSHOT.jar 27 | ``` -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | file-demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | file-demo 12 | Spring Boot PDF Crop 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.0.RELEASE 18 | 19 | 20 | 21 | 22 | 23 | UTF-8 24 | UTF-8 25 | 1.8 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-test 39 | test 40 | 41 | 42 | opencv 43 | opencv 44 | 3.4.2 45 | 46 | 47 | com.lowagie 48 | itext 49 | 4.2.2 50 | 51 | 52 | 53 | 54 | 55 | org.apache.pdfbox 56 | pdfbox 57 | 1.8.15 58 | 59 | 60 | 61 | 62 | 63 | 64 | org.apache.commons 65 | commons-io 66 | 1.3.2 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | org.springframework.boot 76 | spring-boot-maven-plugin 77 | 78 | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /src/main/java/com/example/filedemo/FileDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.filedemo; 2 | 3 | import com.example.filedemo.property.FileStorageProperties; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 7 | 8 | @SpringBootApplication 9 | @EnableConfigurationProperties({ 10 | FileStorageProperties.class 11 | }) 12 | public class FileDemoApplication { 13 | 14 | public static void main(String[] args) { 15 | SpringApplication.run(FileDemoApplication.class, args); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/example/filedemo/controller/FileController.java: -------------------------------------------------------------------------------- 1 | package com.example.filedemo.controller; 2 | 3 | import com.example.filedemo.extraction.ExtractPdfSignature; 4 | import com.example.filedemo.payload.UploadFileResponse; 5 | import com.example.filedemo.service.FileStorageService; 6 | 7 | import java.io.File; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.core.io.Resource; 12 | import org.springframework.http.HttpHeaders; 13 | import org.springframework.http.MediaType; 14 | import org.springframework.http.ResponseEntity; 15 | import org.springframework.web.bind.annotation.*; 16 | import org.springframework.web.multipart.MultipartFile; 17 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 18 | 19 | import javax.servlet.http.HttpServletRequest; 20 | import java.io.IOException; 21 | import java.net.URISyntaxException; 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | import javax.servlet.ServletContext; 25 | import org.apache.commons.io.FileUtils; 26 | import org.springframework.core.io.ResourceLoader; 27 | import org.springframework.core.io.support.ResourcePatternUtils; 28 | 29 | @RestController 30 | public class FileController { 31 | 32 | private static final Logger logger = LoggerFactory.getLogger(FileController.class); 33 | 34 | @Autowired 35 | private FileStorageService fileStorageService; 36 | 37 | @Autowired 38 | ServletContext servletContext; 39 | 40 | @Autowired 41 | private ResourceLoader resourceLoader; 42 | 43 | @PostMapping("/uploadFile") 44 | public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) throws URISyntaxException, IOException, Exception { 45 | 46 | // List traindata=new ArrayList(); 47 | // Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath*:static/train/*.*"); 48 | // for (Resource r : resources) { 49 | // traindata.add(r.getFile()); 50 | // } 51 | 52 | String fileNamedel = fileStorageService.storeFile(file); 53 | 54 | Resource resourcedel = fileStorageService.loadFileAsResource(fileNamedel); 55 | 56 | String path = resourcedel.getFile().getAbsolutePath(); 57 | int lastindex = path.lastIndexOf("/"); 58 | path = path.substring(0, lastindex + 1); 59 | 60 | File destinationFile = new File(path); 61 | FileUtils.cleanDirectory(destinationFile); 62 | 63 | String fileName = fileStorageService.storeFile(file); 64 | Resource resource = fileStorageService.loadFileAsResource(fileName); 65 | String filenameret = ExtractPdfSignature.extractSignature(resource); 66 | filenameret = filenameret + ".pdf"; 67 | String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath() 68 | .path("/downloadFile/") 69 | .path(filenameret) 70 | .toUriString(); 71 | return new UploadFileResponse(filenameret, fileDownloadUri, 72 | file.getContentType(), file.getSize()); 73 | } 74 | 75 | // @PostMapping("/uploadMultipleFiles") 76 | // public List uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) { 77 | // return Arrays.asList(files) 78 | // .stream() 79 | // .map(file -> uploadFile(file)) 80 | // .collect(Collectors.toList()); 81 | // } 82 | @GetMapping("/downloadFile/{fileName:.+}") 83 | public ResponseEntity downloadFile(@PathVariable String fileName, HttpServletRequest request) { 84 | // Load file as Resource 85 | Resource resource = fileStorageService.loadFileAsResource(fileName); 86 | 87 | // Try to determine file's content type 88 | String contentType = null; 89 | try { 90 | contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); 91 | } catch (IOException ex) { 92 | logger.info("Could not determine file type."); 93 | } 94 | 95 | // Fallback to the default content type if type could not be determined 96 | if (contentType == null) { 97 | contentType = "application/octet-stream"; 98 | } 99 | 100 | return ResponseEntity.ok() 101 | .contentType(MediaType.parseMediaType(contentType)) 102 | .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") 103 | .body(resource); 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/example/filedemo/exception/FileStorageException.java: -------------------------------------------------------------------------------- 1 | package com.example.filedemo.exception; 2 | 3 | public class FileStorageException extends RuntimeException { 4 | public FileStorageException(String message) { 5 | super(message); 6 | } 7 | 8 | public FileStorageException(String message, Throwable cause) { 9 | super(message, cause); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/example/filedemo/exception/MyFileNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.example.filedemo.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | @ResponseStatus(HttpStatus.NOT_FOUND) 7 | public class MyFileNotFoundException extends RuntimeException { 8 | public MyFileNotFoundException(String message) { 9 | super(message); 10 | } 11 | 12 | public MyFileNotFoundException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/example/filedemo/extraction/ExtractPdfSignature.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.filedemo.extraction; 7 | 8 | import com.itextpdf.text.Document; 9 | import com.itextpdf.text.Image; 10 | import com.itextpdf.text.Rectangle; 11 | import com.itextpdf.text.pdf.PdfWriter; 12 | import java.awt.image.BufferedImage; 13 | import java.io.File; 14 | import java.io.FileInputStream; 15 | import java.io.FileOutputStream; 16 | import java.io.InputStream; 17 | import java.nio.file.Paths; 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | import javax.imageio.ImageIO; 21 | import org.apache.pdfbox.pdmodel.PDDocument; 22 | import org.apache.pdfbox.pdmodel.PDPage; 23 | 24 | import org.opencv.core.Core; 25 | import org.springframework.core.io.ClassPathResource; 26 | import org.springframework.core.io.Resource; 27 | 28 | /** 29 | * 30 | * @author appcino 31 | */ 32 | public class ExtractPdfSignature { 33 | 34 | public static String extractSignature(Resource resource) throws Exception { 35 | 36 | System.loadLibrary(Core.NATIVE_LIBRARY_NAME); 37 | // String filepath = "/home/appcino/Downloads/pdfimages/test/SAMPLE PDF.pdf"; 38 | // File sourceFile = new File(filepath); 39 | String filename = resource.getFilename(); 40 | int index = filename.indexOf(".pdf"); 41 | filename = filename.substring(0, index); 42 | filename = filename.replaceAll("%20"," "); 43 | 44 | System.out.println("remove all space bet filename : "+filename); 45 | //InputStream ins = new FileInputStream(sourceFile); 46 | List traindata2 = new ArrayList<>(); 47 | boolean flagpdf2img = convertpdftoimage(resource.getFile()); 48 | if (flagpdf2img) { 49 | 50 | File file = new File("/home/appcino/Downloads/sprintbootextractpdf/train/"); 51 | 52 | File[] files = file.listFiles(); 53 | 54 | for (File f : files) { 55 | traindata2.add(f.getAbsolutePath()); 56 | } 57 | String path = resource.getFile().getAbsolutePath(); 58 | int lastindex=path.lastIndexOf("/"); 59 | path=path.substring(0, lastindex+1); 60 | String infileocv = path+"" + filename + ".jpeg"; 61 | String outfileocv = path+"" + filename + "-crop.jpeg"; 62 | ObjectMatching objmatch = new ObjectMatching(); 63 | boolean flagmatch = objmatch.matchOperation(infileocv, traindata2, outfileocv); 64 | System.out.println("Template Matching :::::"+flagmatch); 65 | 66 | if (flagmatch) { 67 | //String destDir = "/home/appcino/Downloads/pdfimages/result/"; 68 | //convertImgToPDF(outfile, filename, destDir); 69 | convertimg2pdf(outfileocv, filename, path); 70 | } 71 | } 72 | return filename; 73 | } 74 | 75 | 76 | 77 | public static boolean convertpdftoimage(File sourceFile) { 78 | boolean flag = false; 79 | try { 80 | //String sourceDir = "/home/appcino/Downloads/pdfimages/test/" + filename + ".pdf"; // Pdf files are read from this folder 81 | //String destinationDir = "/home/appcino/Downloads/pdfimages/temp/"; // converted images from pdf document are saved here 82 | String path = sourceFile.getAbsolutePath(); 83 | int lastindex=path.lastIndexOf("/"); 84 | path=path.substring(0, lastindex+1); 85 | //File sourceFile = new File(infile); 86 | File destinationFile = new File(path); 87 | if (!destinationFile.exists()) { 88 | destinationFile.mkdir(); 89 | System.out.println("Folder Created -> " + destinationFile.getAbsolutePath()); 90 | } else { 91 | //FileUtils.cleanDirectory(destinationFile); 92 | } 93 | if (sourceFile.exists()) { 94 | System.out.println("Images copied to Folder: " + destinationFile.getName()); 95 | PDDocument document = PDDocument.load(sourceFile); 96 | List list = document.getDocumentCatalog().getAllPages(); 97 | System.out.println("Total files to be converted -> " + list.size()); 98 | 99 | String fileName = sourceFile.getName().replace(".pdf", ""); 100 | int pageNumber = 1; 101 | for (PDPage page : list) { 102 | BufferedImage image = page.convertToImage(); 103 | //File outputfile = new File(destinationDir + fileName + "_" + pageNumber + ".jpeg"); 104 | File outputfile = new File(path + fileName + ".jpeg"); 105 | System.out.println("Image Created -> " + outputfile.getName()); 106 | ImageIO.write(image, "jpeg", outputfile); 107 | pageNumber++; 108 | } 109 | document.close(); 110 | flag = true; 111 | System.out.println("Converted Images are saved at -> " + destinationFile.getAbsolutePath()); 112 | } else { 113 | System.err.println(sourceFile.getName() + " File not exists"); 114 | } 115 | 116 | } catch (Exception e) { 117 | e.printStackTrace(); 118 | } 119 | return flag; 120 | } 121 | 122 | 123 | 124 | public static void convertimg2pdf(String imagePath, String fileName, String destDir) throws Exception { 125 | InputStream in = new FileInputStream(imagePath); 126 | BufferedImage bimg = ImageIO.read(in); 127 | float width = bimg.getWidth(); 128 | float height = bimg.getHeight(); 129 | Rectangle imageSize = new Rectangle(width, height); 130 | Document document = new Document(imageSize, 0, 0, 0, 0); 131 | PdfWriter.getInstance(document, new FileOutputStream(destDir + "/" + fileName + ".pdf")); 132 | document.open(); 133 | Image image = Image.getInstance(imagePath); 134 | //document.add(new Paragraph("Your Heading for the Image Goes Here")); 135 | document.add(image); 136 | document.close(); 137 | } 138 | 139 | public String getParentDirectoryFromJar() { 140 | String dirtyPath = getClass().getResource("").toString(); 141 | String jarPath = dirtyPath.replaceAll("^.*file:/", ""); //removes file:/ and everything before it 142 | jarPath = jarPath.replaceAll("jar!.*", "jar"); //removes everything after .jar, if .jar exists in dirtyPath 143 | jarPath = jarPath.replaceAll("%20", " "); //necessary if path has spaces within 144 | if (!jarPath.endsWith(".jar")) { // this is needed if you plan to run the app using Spring Tools Suit play button. 145 | jarPath = jarPath.replaceAll("/classes/.*", "/classes/"); 146 | } 147 | String directoryPath = Paths.get(jarPath).getParent().toString(); //Paths - from java 8 148 | return directoryPath; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/com/example/filedemo/extraction/TemplateMatching.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.filedemo.extraction; 7 | 8 | /* 9 | * To change this license header, choose License Headers in Project Properties. 10 | * To change this template file, choose Tools | Templates 11 | * and open the template in the editor. 12 | */ 13 | /** 14 | * 15 | * @author appcino 16 | */ 17 | import java.io.File; 18 | import java.io.IOException; 19 | import java.util.List; 20 | import org.opencv.core.Core; 21 | import org.opencv.core.Core.MinMaxLocResult; 22 | import org.opencv.core.CvType; 23 | import org.opencv.core.Mat; 24 | import org.opencv.core.Point; 25 | import org.opencv.core.Rect; 26 | import org.opencv.core.Scalar; 27 | import org.opencv.imgcodecs.Imgcodecs; 28 | import org.opencv.imgproc.Imgproc; 29 | import org.slf4j.Logger; 30 | import org.slf4j.LoggerFactory; 31 | 32 | class ObjectMatching { 33 | private static final Logger logger = LoggerFactory.getLogger(TemplateMatching.class); 34 | public boolean matchOperation(String inFile, List templates, String outFile) throws IOException { 35 | boolean flag = false; 36 | for (String template : templates) { 37 | System.out.println("matching data " + inFile); 38 | System.out.println(template); 39 | System.out.println(outFile); 40 | 41 | flag = run(inFile, template, outFile, Imgproc.TM_CCOEFF_NORMED); 42 | if (flag) { 43 | break; 44 | } 45 | } 46 | return flag; 47 | } 48 | 49 | public boolean run(String inFile, String templateFile, String outFile, 50 | int match_method) { 51 | 52 | boolean flag = false; 53 | System.out.println("\nRunning Template Matching"); 54 | 55 | Mat img = Imgcodecs.imread(inFile); 56 | Mat templ = Imgcodecs.imread(templateFile); 57 | 58 | // / Create the result matrix 59 | int result_cols = img.cols() - templ.cols() + 1; 60 | int result_rows = img.rows() - templ.rows() + 1; 61 | Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1); 62 | 63 | // / Do the Matching and Normalize 64 | Imgproc.matchTemplate(img, templ, result, match_method); 65 | //Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat()); 66 | 67 | // / Localizing the best match with minMaxLoc 68 | MinMaxLocResult mmr = Core.minMaxLoc(result); 69 | 70 | Point matchLoc; 71 | if (match_method == Imgproc.TM_SQDIFF 72 | || match_method == Imgproc.TM_SQDIFF_NORMED) { 73 | matchLoc = mmr.minLoc; 74 | } else { 75 | matchLoc = mmr.maxLoc; 76 | } 77 | 78 | // / Show me what you got 79 | Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(), 80 | matchLoc.y + templ.rows()), new Scalar(255, 255, 255)); 81 | System.out.println(matchLoc.x); 82 | System.out.println(templ.cols()); 83 | System.out.println(matchLoc.y); 84 | System.out.println(templ.rows()); 85 | System.out.println("match score max" + mmr.maxVal); 86 | System.out.println("match score min" + mmr.minVal); 87 | // Save the visualized detection. 88 | double minMatchQuality = 0.8; 89 | if (mmr.maxVal > minMatchQuality) // with CV_TM_SQDIFF_NORMED use minValue < minMatchQuality 90 | { 91 | double[] cord = {matchLoc.x, matchLoc.y, templ.cols(), templ.rows()}; 92 | Rect rectCrop = new Rect(cord); 93 | Mat imageROI = img.submat(rectCrop); 94 | System.out.println("Writing " + outFile); 95 | Imgcodecs.imwrite(outFile, imageROI); 96 | flag = true; 97 | } else { 98 | System.out.println("File Not Matched"); 99 | } 100 | return flag; 101 | } 102 | } 103 | 104 | public class TemplateMatching { 105 | 106 | // public static void main(String[] args) { 107 | // 108 | // //System.loadLibrary("opencv_java300"); 109 | // System.loadLibrary(Core.NATIVE_LIBRARY_NAME); 110 | // String infile = "/home/appcino/Downloads/spring-boot-file-upload-download-rest-api-example-master/uploads/SIG CARD - PR.jpeg"; 111 | // String template = "/home/appcino/Downloads/pdfimages/form3_sig.jpeg"; 112 | // String outfile = "/home/appcino/Downloads/pdfimages/form3_sigtemp3_1_2.jpeg"; 113 | // 114 | // //new MatchingDemo().run(args[0], args[1], args[2], Imgproc.TM_CCOEFF); 115 | // new ObjectMatching().run(infile, template, outfile, Imgproc.TM_CCOEFF_NORMED); 116 | // } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/com/example/filedemo/payload/UploadFileResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.filedemo.payload; 2 | 3 | 4 | public class UploadFileResponse { 5 | private String fileName; 6 | private String fileDownloadUri; 7 | private String fileType; 8 | private long size; 9 | 10 | public UploadFileResponse(String fileName, String fileDownloadUri, String fileType, long size) { 11 | this.fileName = fileName; 12 | this.fileDownloadUri = fileDownloadUri; 13 | this.fileType = fileType; 14 | this.size = size; 15 | } 16 | 17 | public String getFileName() { 18 | return fileName; 19 | } 20 | 21 | public void setFileName(String fileName) { 22 | this.fileName = fileName; 23 | } 24 | 25 | public String getFileDownloadUri() { 26 | return fileDownloadUri; 27 | } 28 | 29 | public void setFileDownloadUri(String fileDownloadUri) { 30 | this.fileDownloadUri = fileDownloadUri; 31 | } 32 | 33 | public String getFileType() { 34 | return fileType; 35 | } 36 | 37 | public void setFileType(String fileType) { 38 | this.fileType = fileType; 39 | } 40 | 41 | public long getSize() { 42 | return size; 43 | } 44 | 45 | public void setSize(long size) { 46 | this.size = size; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/example/filedemo/property/FileStorageProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.filedemo.property; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | @ConfigurationProperties(prefix = "file") 6 | public class FileStorageProperties { 7 | private String uploadDir; 8 | 9 | public String getUploadDir() { 10 | return uploadDir; 11 | } 12 | 13 | public void setUploadDir(String uploadDir) { 14 | this.uploadDir = uploadDir; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/example/filedemo/service/FileStorageService.java: -------------------------------------------------------------------------------- 1 | package com.example.filedemo.service; 2 | 3 | import com.example.filedemo.exception.FileStorageException; 4 | import com.example.filedemo.exception.MyFileNotFoundException; 5 | import com.example.filedemo.property.FileStorageProperties; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.core.io.Resource; 8 | import org.springframework.core.io.UrlResource; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.util.StringUtils; 11 | import org.springframework.web.multipart.MultipartFile; 12 | import java.io.IOException; 13 | import java.net.MalformedURLException; 14 | import java.nio.file.Files; 15 | import java.nio.file.Path; 16 | import java.nio.file.Paths; 17 | import java.nio.file.StandardCopyOption; 18 | 19 | @Service 20 | public class FileStorageService { 21 | 22 | private final Path fileStorageLocation; 23 | 24 | @Autowired 25 | public FileStorageService(FileStorageProperties fileStorageProperties) { 26 | this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()) 27 | .toAbsolutePath().normalize(); 28 | 29 | try { 30 | Files.createDirectories(this.fileStorageLocation); 31 | } catch (Exception ex) { 32 | throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex); 33 | } 34 | } 35 | 36 | public String storeFile(MultipartFile file) { 37 | // Normalize file name 38 | String fileName = StringUtils.cleanPath(file.getOriginalFilename()); 39 | 40 | try { 41 | // Check if the file's name contains invalid characters 42 | if(fileName.contains("..")) { 43 | throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName); 44 | } 45 | 46 | // Copy file to the target location (Replacing existing file with the same name) 47 | Path targetLocation = this.fileStorageLocation.resolve(fileName); 48 | Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); 49 | 50 | return fileName; 51 | } catch (IOException ex) { 52 | throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex); 53 | } 54 | } 55 | 56 | public Resource loadFileAsResource(String fileName) { 57 | try { 58 | Path filePath = this.fileStorageLocation.resolve(fileName).normalize(); 59 | Resource resource = new UrlResource(filePath.toUri()); 60 | if(resource.exists()) { 61 | return resource; 62 | } else { 63 | throw new MyFileNotFoundException("File not found " + fileName); 64 | } 65 | } catch (MalformedURLException ex) { 66 | throw new MyFileNotFoundException("File not found " + fileName, ex); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | ## MULTIPART (MultipartProperties) 2 | # Enable multipart uploads 3 | spring.servlet.multipart.enabled=true 4 | # Threshold after which files are written to disk. 5 | spring.servlet.multipart.file-size-threshold=2KB 6 | # Max file size. 7 | spring.servlet.multipart.max-file-size=200MB 8 | # Max Request Size 9 | spring.servlet.multipart.max-request-size=215MB 10 | 11 | ## File Storage Properties 12 | file.upload-dir=./uploads 13 | file.temp-dir=./temp 14 | 15 | #server.address=localhost 16 | server.port=8080 17 | 18 | 19 | #logging.level.root= ERROR 20 | #logging.level.org.springframework.security= DEBUG 21 | #logging.level.org.springframework.web= ERROR 22 | #logging.level.org.hibernate= DEBUG 23 | #logging.level.org.apache.commons.dbcp2= DEBUG 24 | #logging.file = /home/appcino/Downloads/pdfimages/mylogfile.html 25 | #logging.appender.file.layout=org.apache.log4j.PatternLayout 26 | #logging.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n -------------------------------------------------------------------------------- /src/main/resources/static/css/main.css: -------------------------------------------------------------------------------- 1 | * { 2 | -webkit-box-sizing: border-box; 3 | -moz-box-sizing: border-box; 4 | box-sizing: border-box; 5 | } 6 | 7 | body { 8 | margin: 0; 9 | padding: 0; 10 | font-weight: 400; 11 | font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; 12 | font-size: 1rem; 13 | line-height: 1.58; 14 | color: #333; 15 | background-color: #f4f4f4; 16 | } 17 | 18 | body:before { 19 | height: 50%; 20 | width: 100%; 21 | position: absolute; 22 | top: 0; 23 | left: 0; 24 | background: #128ff2; 25 | content: ""; 26 | z-index: 0; 27 | } 28 | 29 | .clearfix:after { 30 | display: block; 31 | content: ""; 32 | clear: both; 33 | } 34 | 35 | 36 | h1, h2, h3, h4, h5, h6 { 37 | margin-top: 20px; 38 | margin-bottom: 20px; 39 | } 40 | 41 | h1 { 42 | font-size: 1.7em; 43 | } 44 | 45 | a { 46 | color: #128ff2; 47 | } 48 | 49 | button { 50 | box-shadow: none; 51 | border: 1px solid transparent; 52 | font-size: 14px; 53 | outline: none; 54 | line-height: 100%; 55 | white-space: nowrap; 56 | vertical-align: middle; 57 | padding: 0.6rem 1rem; 58 | border-radius: 2px; 59 | transition: all 0.2s ease-in-out; 60 | cursor: pointer; 61 | min-height: 38px; 62 | } 63 | 64 | button.primary { 65 | background-color: #128ff2; 66 | box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12); 67 | color: #fff; 68 | } 69 | 70 | input { 71 | font-size: 1rem; 72 | } 73 | 74 | input[type="file"] { 75 | border: 1px solid #128ff2; 76 | padding: 6px; 77 | max-width: 100%; 78 | } 79 | 80 | .file-input { 81 | width: 100%; 82 | } 83 | 84 | .submit-btn { 85 | display: block; 86 | margin-top: 15px; 87 | min-width: 100px; 88 | } 89 | 90 | @media screen and (min-width: 500px) { 91 | .file-input { 92 | width: calc(100% - 115px); 93 | } 94 | 95 | .submit-btn { 96 | display: inline-block; 97 | margin-top: 0; 98 | margin-left: 10px; 99 | } 100 | } 101 | 102 | 103 | .upload-container { 104 | max-width: 750px; 105 | margin-left: auto; 106 | margin-right: auto; 107 | background-color: #fff; 108 | box-shadow: 0 1px 11px rgba(0, 0, 0, 0.27); 109 | margin-top: 60px; 110 | min-height: 400px; 111 | position: relative; 112 | padding: 20px; 113 | } 114 | 115 | .upload-header { 116 | border-bottom: 1px solid #ececec; 117 | } 118 | 119 | .upload-header h2 { 120 | font-weight: 500; 121 | } 122 | 123 | .single-upload { 124 | padding-bottom: 20px; 125 | margin-bottom: 20px; 126 | border-bottom: 1px solid #e8e8e8; 127 | } 128 | 129 | .upload-response { 130 | overflow-x: hidden; 131 | word-break: break-all; 132 | } 133 | -------------------------------------------------------------------------------- /src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Upload PDF File To Crop 6 | 7 | 8 | 9 | 12 |
13 |
14 |

Upload PDF File To Crop

15 |
16 |
17 |
18 |

Upload Single File

19 |
20 | 21 | 22 |
23 |
24 |
25 |
26 |
27 |
28 | 39 |
40 |
41 | 42 | 43 | -------------------------------------------------------------------------------- /src/main/resources/static/js/main.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var singleUploadForm = document.querySelector('#singleUploadForm'); 4 | var singleFileUploadInput = document.querySelector('#singleFileUploadInput'); 5 | var singleFileUploadError = document.querySelector('#singleFileUploadError'); 6 | var singleFileUploadSuccess = document.querySelector('#singleFileUploadSuccess'); 7 | 8 | var multipleUploadForm = document.querySelector('#multipleUploadForm'); 9 | var multipleFileUploadInput = document.querySelector('#multipleFileUploadInput'); 10 | var multipleFileUploadError = document.querySelector('#multipleFileUploadError'); 11 | var multipleFileUploadSuccess = document.querySelector('#multipleFileUploadSuccess'); 12 | 13 | function uploadSingleFile(file) { 14 | var formData = new FormData(); 15 | formData.append("file", file); 16 | 17 | var xhr = new XMLHttpRequest(); 18 | xhr.open("POST", "/uploadFile"); 19 | 20 | xhr.onload = function() { 21 | console.log(xhr.responseText); 22 | var response = JSON.parse(xhr.responseText); 23 | if(xhr.status == 200) { 24 | singleFileUploadError.style.display = "none"; 25 | singleFileUploadSuccess.innerHTML = "

File Cropped Successfully.

DownloadUrl : " + response.fileDownloadUri + "

"; 26 | singleFileUploadSuccess.style.display = "block"; 27 | } else { 28 | singleFileUploadSuccess.style.display = "none"; 29 | singleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred"; 30 | } 31 | } 32 | 33 | xhr.send(formData); 34 | } 35 | 36 | function uploadMultipleFiles(files) { 37 | var formData = new FormData(); 38 | for(var index = 0; index < files.length; index++) { 39 | formData.append("files", files[index]); 40 | } 41 | 42 | var xhr = new XMLHttpRequest(); 43 | xhr.open("POST", "/uploadMultipleFiles"); 44 | 45 | xhr.onload = function() { 46 | console.log(xhr.responseText); 47 | var response = JSON.parse(xhr.responseText); 48 | if(xhr.status == 200) { 49 | multipleFileUploadError.style.display = "none"; 50 | var content = "

All Files Uploaded Successfully

"; 51 | for(var i = 0; i < response.length; i++) { 52 | content += "

DownloadUrl : " + response[i].fileDownloadUri + "

"; 53 | } 54 | multipleFileUploadSuccess.innerHTML = content; 55 | multipleFileUploadSuccess.style.display = "block"; 56 | } else { 57 | multipleFileUploadSuccess.style.display = "none"; 58 | multipleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred"; 59 | } 60 | } 61 | 62 | xhr.send(formData); 63 | } 64 | 65 | singleUploadForm.addEventListener('submit', function(event){ 66 | var files = singleFileUploadInput.files; 67 | if(files.length === 0) { 68 | singleFileUploadError.innerHTML = "Please select a file"; 69 | singleFileUploadError.style.display = "block"; 70 | } 71 | uploadSingleFile(files[0]); 72 | event.preventDefault(); 73 | }, true); 74 | 75 | 76 | multipleUploadForm.addEventListener('submit', function(event){ 77 | var files = multipleFileUploadInput.files; 78 | if(files.length === 0) { 79 | multipleFileUploadError.innerHTML = "Please select at least one file"; 80 | multipleFileUploadError.style.display = "block"; 81 | } 82 | uploadMultipleFiles(files); 83 | event.preventDefault(); 84 | }, true); 85 | 86 | -------------------------------------------------------------------------------- /src/main/resources/static/train/SAMPLE PDF.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/src/main/resources/static/train/SAMPLE PDF.jpeg -------------------------------------------------------------------------------- /src/main/resources/static/train/SIG CARD - PR_1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/src/main/resources/static/train/SIG CARD - PR_1.jpeg -------------------------------------------------------------------------------- /src/main/resources/static/train/SIG-CARD.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/src/main/resources/static/train/SIG-CARD.jpeg -------------------------------------------------------------------------------- /src/main/resources/static/train/form3_sig.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/src/main/resources/static/train/form3_sig.jpeg -------------------------------------------------------------------------------- /src/main/resources/static/train/noimage.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/src/main/resources/static/train/noimage.jpeg -------------------------------------------------------------------------------- /src/main/resources/static/train/passport3_1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/src/main/resources/static/train/passport3_1.jpeg -------------------------------------------------------------------------------- /src/test/java/com/example/filedemo/FileDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.filedemo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class FileDemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /train/SAMPLE PDF.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/train/SAMPLE PDF.jpeg -------------------------------------------------------------------------------- /train/SIG CARD - PR_1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/train/SIG CARD - PR_1.jpeg -------------------------------------------------------------------------------- /train/SIG-CARD.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/train/SIG-CARD.jpeg -------------------------------------------------------------------------------- /train/form3_sig.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/train/form3_sig.jpeg -------------------------------------------------------------------------------- /train/noimage.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/train/noimage.jpeg -------------------------------------------------------------------------------- /train/passport3_1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MuhamedHabib/springboot-opencv/f0107e22069d51ab8f3e452cb93f616e3e66c382/train/passport3_1.jpeg --------------------------------------------------------------------------------