Spring MVC receives uploaded pictures and stores them in the local directory

Time:2020-5-25

Preface: Project Environment

This simple demo is based onSpring MVC frameworkOn, the deployment environment istomcat, bootstrap + jQuery used in the previous section_ file_ Upload component. The way to store pictures is to store them in the virtual directory and return the path to the virtual directory. It is recommended to match the spring MVC environment before continuing to refer to this blog. If you don’t have a good environment, please refer to this blog

Picture storage mode

Before giving the code of uploading pictures, first explain the idea of receiving pictures from the server. There are generally two ways to save pictures on the server side.

  1. Store the pictures in the database in the form of blob, which is only applicable to the scenes with smaller pictures
  2. Store the pictures in the directory of the server, and store the picture path and access URL in the database. The disadvantage is that the performance of the server may be degraded
  3. Store the pictures in any path other than the server directory, configure the virtual directory in the server, and access the pictures in the picture directory through the virtual directory

Here I will mainly talk about how to realize the third kind of image storage.
In the development environment, you can directly use IntelliJ to configure the Tomcat virtual directory. Because Tomcat under IntelliJ management is actually a Tomcat virtual image, the configuration in IntelliJ will not affect the configuration in the actual Tomcat. So if you are directly using IntelliJ to deploy a project during the development and testing process, please refer to IntelliJ to configure the virtual directory. If the developed war package is deployed directly in the server, refer to Tomcat to configure the virtual directory.

Configure virtual directory in IntelliJ

Spring MVC receives uploaded pictures and stores them in the local directory

Spring MVC receives uploaded pictures and stores them in the local directory
Enter the Tomcat configuration management page, click the deployment tab, and then click the plus sign in the lower left corner to select “external source”, and add the real path of the corresponding virtual directory. Finally, configure the access path of the virtual directory in the application context.

Configure virtual directory in Tomcat

There are many ways to configure virtual directory in Tomcat. Please refer to these two blogs for details
http://www.cnblogs.com/love54…
https://my.oschina.net/liangz…
The method I want to introduce here is to configure a separate virtual directory in Catalina.
Spring MVC receives uploaded pictures and stores them in the local directory

Spring MVC receives uploaded pictures and stores them in the local directory
Find / Tomcat_ Home / conf / Catalina / localhost folder. Create a new XML file under the folder. The file name of the XML file is the access path name corresponding to the virtual directory. If multi-level directory is needed, use ා, for example, PSM# pc.xml The corresponding access path is / PSM / pic. Configure the virtual directory in the XML file with the following syntax

<Context docBase=”/users/rale/Documents/images” reloadable=”false” ></Context>
Reloadale means whether to reload if it changes. After the configuration, you can access the virtual directory directly with this path without restarting the server.

Picture upload and receive

On the front end, use bootstrap and juery_ file_ The upload plug-in uploads images. The simple HTML page is as follows

<!DOCTYPE html>
    <html>
        ...
        <label for="cover"><img></label>
        <input type="file" id="cover" data-url="/psm/image/upload"/>
        <%--ImageUpload--%>
        <spring:url value="/resources/plugins/jQuery/jQuery-2.1.4.min.js" var="jquery_js"/>
        <script></script>
        <spring:url value="/resources/plugins/jQueryFileupload/js/vendor/jquery.ui.widget.js" var="jquery_ui_widget_js"/>
        <spring:url value="/resources/plugins/jQueryFileupload/js/jquery.iframe-transport.js" var="jquery_iframe_transport_js"/>
        <spring:url value="/resources/plugins/jQueryFileupload/js/jquery.fileupload.js" var="jquery_fileupload_js"/>
        <script></script>
        <script></script>
        <script></script>
        
        <! -- use jquery_ file_ Upload plug-in -- >
        <script>
            $(function () {
            $('#cover').fileupload({
                dataType: 'json',

                done: function (e, data) {
                    if(data.result != null){
                        console.log(data.result.fileURL)
                        $('label[for="cover"] img').attr('src', data.result.fileURL)
                    }
                },

            });
        });
        </script>
    </html>

The controller receives the request to upload the file. You can refer to this blog here
The code of Java storage file is as follows. This method converts the byte stream of pictures into files and stores them in the corresponding picture path, which is the virtual directory we configured before.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * Created by rale on 5/29/17.
 *Store pictures locally
 */
public class FileUtil {

    public static void save(byte[] bytes, String fileName, String path) throws IOException {
        createDirectory(path);
        FileOutputStream os = new FileOutputStream(path + fileName);
        os.write(bytes);
        os.close();
    }

    private static boolean isExistPath(String path) {
        File file = new File(path);
        if ( file.exists ()) {// determine the existence of the file directory
            return true;
        }else{
            return false;
        }
    }
    private static void createDirectory(String path){
        if(!isExistPath(path)){
            File file=new File(path);
            file.mkdirs();
        }
    }
}

Spring MVC receives uploaded pictures and stores them in the local directory
For more development techniques, interview tutorials and Internet Co push, please welcome my WeChat official account. The welfare will be paid irregularly~

Recommended Today

Please stop using JWT for session management immediately

introduction Recently, it has been found that many web application systems use JWT for session management. The reason is to avoid storing sessions on the server or to pursue independent control. I don’t know that there are huge security risks in using JWT for session management! HTTP session management Let’s talk about HTTP protocol first. […]