Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How SpringBoot uploads a picture to a specified location and returns URL

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how SpringBoot uploads pictures to a specified location and returns URL. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Demand

Upload the front-end image to the file directory specified by the server, and return the URL to the front-end

Front end part (ElementUI+Vue.js)

Import and use of ElementUI: (component | Element)

Import and use of Vue.js: (Vue.js (vuejs.org))

Click upload to upload only jpg/png files, and do not exceed 500kb export default {name: "updateImg", methods: {handlePreview (file) {window.open (file.response.url); console.log (file.response.url);}

Effect:

Back-end part (SpringBoot) 1. Configure the application.yml file first

File-save-path: the location of the picture to be saved encountered a 404 problem in the morning because the path could not be matched because the last images was not added to the last images when configuring the images.

Server: port: 8081 file-save-path: d:\ SoftWare\ SpringToolSuite\ WorkPlace\ HelloWorld\ src\ main\ resources\ static\ images\ spring: mvc: view: prefix: / suffix: .jsp2. Mapping resources-overrides the WebMvcConfigurer interface to map resources to package com.etc.config;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configurationpublic class WebConfig implements WebMvcConfigurer {@ Value ("${file-save-path}") private String fileSavePath @ Override public void addResourceHandlers (ResourceHandlerRegistry registry) {registry.addResourceHandler ("/ images/**") .addResourceLocations ("file:" + fileSavePath); / / System.out.println ("file:" + fileSavePath);}}

AddResourceHandler ("/ images/**") means that if a request is initiated with / images/ path, it will be mapped according to the path of addResourceLocations ("file:" + fileSavePath).

For example, there is a url: http://localhost:8081/images/Hello.jpg

Indicates that you want to request access to Hello.jpg. At this time, the server will map the requested resource to the path we configured, that is, it will go to fileSavePath to find out whether there is a Hello.jpg resource and return it to the front-end page.

3.Controller code

Here, in order to facilitate the return using Map, the encapsulated type is used in the actual development.

Package com.etc.controller;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import javax.sound.midi.SysexMessage;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController Import org.springframework.web.multipart.MultipartFile;@CrossOrigin@RestControllerpublic class ImgUploadController {SimpleDateFormat sdf = new SimpleDateFormat ("/ yyyy.MM.dd/"); @ Value ("${file-save-path}") private String fileSavePath; @ PostMapping ("/ upload") public Map fileupload (MultipartFile file,HttpServletRequest req) {Map result = new HashMap () / / get the file name String originName = file.getOriginalFilename (); System.out.println ("originName:" + originName); / / determine the file type if (! originName.endsWith (".jpg")) {result.put ("status", "error") Result.put ("msg", "incorrect file type"); return result;} / / create a new directory for uploaded files String format = sdf.format (new Date ()); String realPath = fileSavePath + format; System.out.println ("realPath:" + realPath) / / if the directory does not exist, create a directory File folder = new File (realPath); if (! Folder.exists () {folder.mkdirs ();} / / give the uploaded file a new name and avoid repeating the name String newName = UUID.randomUUID (). ToString () + ".jpg" Try {/ / generate files, folder is the file directory, and newName is the file name file.transferTo (new File (folder,newName)) / / generate url String url = req.getScheme () + ": / /" + req.getServerName () + ":" + req.getServerPort () + "/ images" + format + newName; System.out.println ("url:" + url) returned to the front end / / return URL result.put ("status", "success"); result.put ("url", url);} catch (IOException e) {/ / TODO Auto-generated catch block result.put ("status", "error") Result.put ("msg", e.getMessage ());} return result }} this is the end of the article on "how SpringBoot uploads pictures to a specified location and returns URL". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report