Reprinted: https://blog.csdn.net/weixin_40337982/article/details/84031778
Part very helpful to me reprint record
First, html page:
<-! Form is to add the enctype of -> <form class="form-horizontal" enctype="multipart/form-data"> <div v-if="menu.type == 1" class="form-group"> <div class="col-sm-2 control-label">图片</div> <div class="col-sm-10"> <div class="ui-upfile"> <div style="width: 150px;height: 140px;display:none;" class="file-area" /> </div> <input type="hidden" name="menuImgUrl" class="menu-image-url" v-model="menu.menuImgUrl"> <input type='button' class='btn' value='上传图片'οnclick="document.getElementById('file').click()" style=""/> <input type="file" class="menu-image-url" value="" id="file" @change="onUpload" style="filter:alpha(opacity:0);opacity:0;width:0px"> </div> </div> </div>
Here to explain, is due to the use of vue, where all values are assigned using the v-model, then why are there so many input box here,
the first is the return value of the property I object;
the second is handwriting a button, because if used directly input type = file, then compare ugly style, there will be a document that the word is not selected, you can type = input file that in turn is necessary.
So here we use a button to override type = file functions, and the input type = file is hidden, where the core code is: opacity: 0;
Next, js Code:
onUpload (e) { were files = e.target.files [ 0 ]; was form file = new shape data (); formFile.append("file", files); $.ajax({ url: baseURL + ' SYS / the Upload / uploadPic ' , // This is the file upload interface requests the background of the type: ' POST ' , dataType: 'json', cache: false , data: formFile, processData: false, contentType: false, success: function(r){ if (r.code === 0) { vm.menu.menuImgUrl = r.fileUrl; $(".file-area").css("display","block"); $(".file-area").html("<img src= '"+ r.fileUrl +"'>"); }else{ Alert ( " File upload failed: " + r.msg); } } }); }
The use of the vue, so here is written in the methods below.
Here is the main request background, to transfer files over, and then returns a url, we can access the pictures by the url directly.
Class background UploadController
@RestController @RequestMapping("/sys/upload") public class UploadController extends BaseController { /** * upload image * @param file * @param request * @throws IOException */ @RequestMapping( value = "/uploadPic") @ResponseBody public R uploadPic (@RequestParam (value = " File " , required = false ) MultipartFile File, the HttpServletRequest Request) throws IOException { // currently there is a local hard-coded path of String path = " D: / img " ; logger.info ( " path: " + path); // get the file name String fileName = file.getOriginalFilename (); // get the file name suffix Calendar currTime = Calendar.getInstance (); String time = String.valueOf(currTime.get(Calendar.YEAR))+String.valueOf((currTime.get(Calendar.MONTH)+1)); //获取文件名后缀 String suffix = fileName.substring(file.getOriginalFilename().lastIndexOf(".")); suffix = suffix.toLowerCase(); if(suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png")/* || suffix.equals(".gif")*/){ fileName = UUID.randomUUID().toString()+suffix; Targetfile File = new new File (path, fileName); IF (!. TargetFile.getParentFile () EXISTS ()) { // Note that, it is determined whether there is a path to the parent targetFile.getParentFile () mkdirs ().; } Long size = 0 ; // save the try { file.transferTo(targetFile); size = file.getSize(); } catch (Exception e) { e.printStackTrace (); return R.error ( " upload failed! " ); } // item url, or constants may be used herein to obtain the corresponding dictionary data url prefix; String fileURL = " HTTP: // localhost: 8080 " ; // file for the path fileURL = fileURL request.getContextPath + () + " / IMG / " + fileName; logger.info("fileUrl:" + fileUrl); return R.ok().put("fileUrl", fileUrl); } The else { return R.error ( " image formats in error, please upload .jpg, .png, .jpeg file format " ); } } }
Here is a pit, that is due to the use of the built-tomcat spring boot, so the compiler automatically generates a path in the system tray, something like this:
C:\Users\69223\AppData\Local\Temp\tomcat-docbase.6718506550492189172.8080
But put the files on this below, we are unable to acquire the right, but tomcat generated folder where the middle section of numbers also are changing. No specific reasons for careful study.
After Baidu and personal understanding of the day, the final decision to use maps;
add the absolute path to be mapped in application.yml file that you want to save the picture here:
#File Upload
cbs:
imagesPath:
file:/D:/img/
yml file format extremely strict requirements must be four spaces, tab key does not work directly cbs.imagesPath.file also being given.
Here is the absolute file path when uploading files to write our upload path;
write WebMvcConfig profile after;
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter{ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/login.html"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); super.addViewControllers( registry ); } /** * Configuration files saved in the configuration file path */ @Value("${cbs.imagesPath}") private String mImagesPath; @Bean public MultipartConfigElement multipartConfigElement(){ Factory's MultipartConfigFactory = new new MultipartConfigFactory (); // maximum file KB, MB factory.setMaxFileSize ( " 1024MB " ); // set the overall total data to be uploaded factory.setMaxRequestSize ( " 1024MB " ); return factory.createMultipartConfig (); } /** * Here is a method of mapping file path */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if(mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")){ String imagesPath = WebMvcConfig.class.getClassLoader().getResource("").getPath(); if(imagesPath.indexOf(".jar")>0){ imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar")); }else if(imagesPath.indexOf("classes")>0){ imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes")); } imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/img/"; mImagesPath = imagesPath; } registry.addResourceHandler("/img/**").addResourceLocations(mImagesPath); super.addResourceHandlers(registry); } }
addResourceHandlers () method is a method of mapping file path;
here we also need to add the following class permissions configuration, i.e., under access control IMG release, or involve rights, is intercepted;
filterMap.put("/img/**", "anon");
Up to here, we upload pictures has basically been completed, you can then enter the test phase.
We upload files to the D drive following img folder, after a successful upload, we use:
HTTP: // localhost: 8080 / project name /img/3b13ad02-3812-4c39-880d-799172801284.png
You can have direct access to our pictures.
Project was started up.
Just basic use, the specific underlying principle, not go into details.
Point a praise it! ^ _ ^!