In springboot during and after the picture or upload files uploaded successfully, but can not access.
In springboot, a store with a relative path, it is only stored in the temporary directory, the file will not have a restart. And after playing for the jar, stored files are also a problem.
In this case, you need to configure a virtual path, mapped to the physical path. For example, there will be a path / usr / upload folder, at the same time as the mapped file server http: // localhost: 8080 / image. Then processing the uploaded file daemon is written under the file / usr / upload folder, accessible via a browser localhost: 8080 / image / xxx.png, equivalent to xxx.png access to / usr / upload folder.
Specific implementation steps - "
Reference blog using the front garden, using the TinyMCE editor. Paste the picture, you can upload.
Instead of using the asynchronous form, so we do not discuss upload tools.
In the back end, the process of uploading handler:
package com.hj.blog.handler; import com.hj.blog.service.UploadService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import java.io.*; @RestController public class UploadHandler { privateLoggerFactory.getLogger Logger = Logger (UploadHandler. Class ); @Autowired Private UploadService uploadService; @ RequestMapping ( "/ uploadimg" ) public String uploadimg (the HttpServletRequest Request) throws IOException, ServletException { // Handler calls the file upload service to get a virtual file path String filepath = uploadService.uploadImg (Request); return filepath; } }
Handling file upload service, in the service upload folders and folders are mapped in a configuration file:
package com.hj.blog.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; @Service public class UploadService { private Logger logger = LoggerFactory.getLogger(UploadService.class); // real path @Value ( "file.uploadFolder $ {}" ) Private String realBasePath; @Value ( "file.accessPath $ {}" ) Private String AccessPath; public String uploadImg (the HttpServletRequest Request) throws IOException, ServletException { inputStream the inputStream = request.getInputStream (); // get the value in the request header of Contect-Type // image suffix String imgSuffix = "PNG" ; the Enumeration Enumeration = request.getHeaderNames (); the while (enumeration.hasMoreElements ()) { String name =(String)enumeration.nextElement(); if(name.equals("content-type")){ String value=request.getHeader(name); imgSuffix = value.split("/")[1]; logger.info("header中" + name + " " + value); logger.info("文件后缀:" + imgSuffix); } } // 文件唯一的名字 String fileName = UUID.randomUUID().toString() + "." +imgSuffix; Date todayDate = new Date(); DateFormat SimpleDateFormat =newSimpleDateFormat ( "yyyy-MM-dd" ); String Today = dateFormat.format (todayDate); // relative path to access the domain name (link accessed through a browser - virtual path) String saveToPath AccessPath + Today + = "/" ; // true path, the path actually stored String = realpath realBasePath + Today + "/" ; // physical file storage path, using local storage path String filepath = realpath + fileName; logger.info ( "upload photos titled:" + fileName + "- the virtual file path:" + saveToPath + "- the physical file path:" + realpath); // decided whether or not the corresponding folder file the destFile = new new file (filepath); if (! destFile.getParentFile () EXISTS ()) {. DestFile.getParentFile () mkdirs ();. } // output stream file to the OutputStream the outputStream = new new a FileOutputStream (the destFile); // buffer byte [] = BS new new byte [1024 ]; int len = -1 ; the while (! (len = InputStream.read (BS)) = -1 ) { OutputStream.write (BS, 0 , len); } inputStream.close (); outputStream.close (); // returns the virtual path to link to visit return saveToPath +fileName; } }
application.properties:
# Upload the map file on your server
file.accessPath = / uploadimg /
# of external exposure to static resources access path
file.staticAccessPath = / uploadimg / **
# file upload directory (note the different directory structure on Linux and Windows)
#file = .uploadFolder / the root / UploadFiles /
file.uploadFolder = C: // File_rec / tmp /
The key configuration class:
package com.hj.blog.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; /** * 设置虚拟路径,访问绝对路径下资源 */ @Configuration public class UploadConfig implements WebMvcConfigurer{ @Value("${file.staticAccessPath}") private String staticAccessPath; @Value("${file.uploadFolder}") private String uploadFolder; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder); } }
By the final configuration class, set up a virtual path to physical path. It can also be normal access pictures.