├── .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 │ │ ├── payload │ │ └── UploadFileResponse.java │ │ ├── property │ │ └── FileStorageProperties.java │ │ └── service │ │ └── FileStorageService.java └── resources │ ├── application.properties │ └── static │ ├── css │ └── main.css │ ├── index.html │ └── js │ └── main.js └── test └── java └── com └── example └── filedemo └── FileDemoApplicationTests.java /.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/callicoder/spring-boot-file-upload-download-rest-api-example/13b64dece35131b4723a63b21888ffa4be059508/.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. Specify the file uploads directory** 14 | 15 | Open `src/main/resources/application.properties` file and change the property `file.upload-dir` to the path where you want the uploaded files to be stored. 16 | 17 | ``` 18 | file.upload-dir=/Users/callicoder/uploads 19 | ``` 20 | 21 | **2. Run the app using maven** 22 | 23 | ```bash 24 | cd spring-boot-file-upload-download-rest-api-example 25 | mvn spring-boot:run 26 | ``` 27 | 28 | That's it! The application can be accessed at `http://localhost:8080`. 29 | 30 | You may also package the application in the form of a jar and then run the jar file like so - 31 | 32 | ```bash 33 | mvn clean package 34 | java -jar target/file-demo-0.0.1-SNAPSHOT.jar 35 | ``` -------------------------------------------------------------------------------- /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 | # https://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 | # Maven 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 Mingw, 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 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /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 File Upload / Download Demo 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.5.5 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 11 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-test 36 | test 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-maven-plugin 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /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.payload.UploadFileResponse; 4 | import com.example.filedemo.service.FileStorageService; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.core.io.Resource; 9 | import org.springframework.http.HttpHeaders; 10 | import org.springframework.http.MediaType; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.web.bind.annotation.*; 13 | import org.springframework.web.multipart.MultipartFile; 14 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 15 | 16 | import javax.servlet.http.HttpServletRequest; 17 | import java.io.IOException; 18 | import java.util.Arrays; 19 | import java.util.List; 20 | import java.util.stream.Collectors; 21 | 22 | @RestController 23 | public class FileController { 24 | 25 | private static final Logger logger = LoggerFactory.getLogger(FileController.class); 26 | 27 | @Autowired 28 | private FileStorageService fileStorageService; 29 | 30 | @PostMapping("/uploadFile") 31 | public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) { 32 | String fileName = fileStorageService.storeFile(file); 33 | 34 | String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath() 35 | .path("/downloadFile/") 36 | .path(fileName) 37 | .toUriString(); 38 | 39 | return new UploadFileResponse(fileName, fileDownloadUri, 40 | file.getContentType(), file.getSize()); 41 | } 42 | 43 | @PostMapping("/uploadMultipleFiles") 44 | public List uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) { 45 | return Arrays.asList(files) 46 | .stream() 47 | .map(file -> uploadFile(file)) 48 | .collect(Collectors.toList()); 49 | } 50 | 51 | @GetMapping("/downloadFile/{fileName:.+}") 52 | public ResponseEntity downloadFile(@PathVariable String fileName, HttpServletRequest request) { 53 | // Load file as Resource 54 | Resource resource = fileStorageService.loadFileAsResource(fileName); 55 | 56 | // Try to determine file's content type 57 | String contentType = null; 58 | try { 59 | contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); 60 | } catch (IOException ex) { 61 | logger.info("Could not determine file type."); 62 | } 63 | 64 | // Fallback to the default content type if type could not be determined 65 | if(contentType == null) { 66 | contentType = "application/octet-stream"; 67 | } 68 | 69 | return ResponseEntity.ok() 70 | .contentType(MediaType.parseMediaType(contentType)) 71 | .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") 72 | .body(resource); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /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/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 | # Please change this to the path where you want the uploaded files to be stored. 13 | file.upload-dir=/Users/callicoder/uploads 14 | -------------------------------------------------------------------------------- /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 | Spring Boot File Upload / Download Rest API Example 6 | 7 | 8 | 9 | 12 |
13 |
14 |

Spring Boot File Upload / Download Rest API Example

15 |
16 |
17 |
18 |

Upload Single File

19 |
20 | 21 | 22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |

Upload Multiple Files

30 |
31 | 32 | 33 |
34 |
35 |
36 |
37 |
38 |
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 Uploaded 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/test/java/com/example/filedemo/FileDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.filedemo; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | public class FileDemoApplicationTests { 8 | 9 | @Test 10 | public void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------