Directory Express
2. Use the mullitypart in spring MVC
1) get the stream of picture file through MultipartFile img
2) use IOUtils to save pictures locally
3. Map local file to URL by configuring WebMvcConfigurerAdapter
4. Test whether the upload is successful through PostMan
1. Import dependency package:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
2. Use the mullitypart in spring MVC
1) get the stream of picture file through MultipartFile img
2) use IOUtils to save pictures locally
The JSON result here is a JSON format using the code generation tool specification.
@RequestMapping("/addSubmit.do") public JSONResult addSubmit(String name,String description,Long schoolid , String remark, MultipartFile img) { Sport model=new Sport(); model.setName(name); model.setDescription(description); model.setSchoolid(schoolid); model.setStatus(false); model.setRemark(remark); InputStream inputStream = null; FileOutputStream outputStream = null; if(img!=null&&img.getSize()>0) { String imgName = UUID.randomUUID().toString() + img.getOriginalFilename(); try { inputStream = img.getInputStream(); outputStream = new FileOutputStream(new File(imgPath + "/" + imgName)); IOUtils.copy(inputStream, outputStream); //Picture name imgName model.setImg(imgName); } catch (IOException e) { e.printStackTrace(); } } service.addSubmit(model); return JSONResult.ok("Add success"); }
3. Map local file to URL by configuring WebMvcConfigurerAdapter
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MyWebMvcConfiguration extends WebMvcConfigurerAdapter { //Configure local file mapping to url @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //override method //Modify tomcat Virtual Map registry.addResourceHandler("/images/**"). addResourceLocations("file:D:/img/");//Define image storage path } }
My photo storage address is as follows:
The access address is URL+ / images /xxx.jpg. The example is as follows:
4. Test whether the upload is successful through PostMan
Here are the fields of the database:
To submit data using PostMan:
Upload picture:
After Send, view the folder directory stored on the server:
Upload succeeded!
This article only provides ideas.