When doing a website development, will inevitably encounter image file to upload and access to, such as a simple example, is the head of the user, how should we upload, how to obtain, which, to a series of problems, such as, in fact, such as image files, stored in the cloud storage space is more appropriate, but the charge, there is more to the local, for example, Firstly, find a place to put your pictures. Here, I take the Upload folder under disk E as an example

The front end provides a form

<form action="/uploadImage" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/> <br>
    <input type="submit" value="Upload">
</form>
Copy the code

After selecting the image, click Upload. In order to achieve the uniqueness of the image, we need to process the name of the image by generating a random name and keeping the extension. We need to intercept the name of the image, as long as the extension (all lowercase) is the part after the last dot

int doPos = file.getOriginalFilename().lastIndexOf("."); // Get the index of the last point

String fileExt= file.getOriginalFilename().substring(doPos + 1).toLowerCase();// Get the extension
Copy the code

Once we get the extension, we generate a unique new name and. The extension name is concatenated to generate a new unique name

String fileName = UUID.randomUUID().toString().replaceAll("-"."") + "." + fileExt;
Copy the code

At this point, the name of the image is processed, and then the core part is to stream the uploaded image to our target folder

Files.copy(file.getInputStream(),new File("E:/upload/" + fileName).toPath());
Copy the code

All right, upload file is done here

How to read the file in the folder, it is relatively easy to read, also do not have to deal with the file name, we just need to copy the path of the target image into the output stream

Files.copy(Paths.get("E:/upload/" + fileName),response.getOutputStream());
Copy the code

In this way, our image exists in the output stream and can be accessed in the browser. According to the following figure, the URL format is as follows

http://127.0.0.1:8080/imgage?fileName=1e43820d9fed45c8a1fb2d786fca0ba0.jpg