springboot + editor achieve picture upload

Wherein
private static final String UPLOADED_FOLDER = "/usr/img/blog/";
Controller layer methods

 @RequestMapping(value="/uploadfile",method=RequestMethod.POST)
    public void hello(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "editormd-image-file", required = false) MultipartFile attach){
        try {
            request.setCharacterEncoding( "utf-8" );
            response.setHeader( "Content-Type" , "text/html" );
            String rootPath = request.getSession().getServletContext().getRealPath("/img/blog/");
            String physicPath=UPLOADED_FOLDER;

            /**
             * 文件路径不存在则需要创建文件路径
             */
            File filePath=new File(rootPath);
            File filePath2=new File(physicPath);
            if(!filePath2.exists()){
                filePath2.mkdirs();
            }
            if(!filePath.exists()){
                filePath.mkdirs();
            }

            //最终文件名
            File realFile=new File(rootPath+File.separator+attach.getOriginalFilename());
            File realFile2=new File(physicPath+File.separator+attach.getOriginalFilename());
            FileUtils.copyInputStreamToFile(attach.getInputStream(), realFile);
            FileUtils.copyInputStreamToFile(attach.getInputStream(), realFile2);

            //下面response返回的json格式是editor.md所限制的,规范输出就OK
            response.getWriter().write( "{\"success\": 1, \"message\":\"上传成功\",\"url\":\"/img/blog/" + attach.getOriginalFilename() + "\"}" );
        } catch (Exception e) {
            try {
                response.getWriter().write( "{\"success\":0}" );
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

Then configure the look config in the conversion path

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 WebMvcConfig extends WebMvcConfigurerAdapter {

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/img/blog/**").addResourceLocations("file:/usr/img/blog/");       
   }

}

Itself is not configured address translation, image upload is stored in a temporary folder inside the tomcat, when the server has restarted, you can not access previously uploaded pictures. So here I come to save the picture to the local, to make a virtual address mapping.
Here Insert Picture Description
Here Insert Picture Description
Here, the address is the address of the virtual image map of tomcat server, but we configured address mapping, so that the server looking for / img / blog document / case will go to find the physical address we configured the.

Guess you like

Origin blog.csdn.net/ouyang_ouba/article/details/89675160