Go directly to the code ( development, framework): idea
SpringBoot
The first is Controller
to write:
package com.xxx.Controller; import com.xxx.Tools.ImgTool; import com.xxx.bean.Msg; import org.apache.tomcat.util.http.fileupload.FileUploadBase; import org.apache.tomcat.util.http.fileupload.FileUploadBase.*; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping(value = "/img") public class ImgUploadController { @PostMapping(value = "/upload") public Msg uploadImg(@RequestParam(value = "img") MultipartFile img, HttpServletRequest request) throws IOException, FileSizeLimitExceededException { if (img == null){ return Msg.fail().add("describe", "参数不能为空"); } else { try { Map<String , Object> map = new HashMap<>(); map = ImgTool.upload(img, request); if (map.get("resultStr").equals("300")){ return Msg.fail().add("describe", "文件格式不支持"); } else { return Msg.success().add("imgurl", map.get("resultStr")); } } catch (Exception e){ return Msg.fail().add("describe", e); } } } }
upload()
The class where the function is located, contains some other tool
methods:
package com.xxx.Tools; import com.xxx.bean.Picture; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class ImgTool { /** * Upload an image and return the image path */ public static Map<String, Object> upload(MultipartFile file, HttpServletRequest request) throws IOException { Map<String, Object> map = new HashMap<>(); // Filter legal file types String fileName = file.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); String allowSuffixs = "gif,jpg,jpeg,bmp,png,ico" ; if (allowSuffixs.indexOf(suffix) == -1 ){ // 300 means the file format does not support map.put("resultStr", "300" ); System.out.println( "The file format is not supported" ); return map; } // Get the real path String localPath = request.getServletContext().getRealPath("/" ); // Create a new directory String uri = File.separator + getNowDateStr(File.separator); File dir = new File(localPath + "/static/ProjectImgs/" + uri); if (!dir.exists()){ dir.mkdirs(); } // Create a new file String newFileName = getUniqueFileName(); File f = new File(dir.getPath() + File.separator + newFileName + "." + suffix); // Copy the data in the input stream to a new file org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), f); // Create a picture object Picture pic = new Picture(); pic.setLocalPath(f.getAbsolutePath()); pic.setName(f.getName()); // Replace \\ in the path with /, in line with the browser's grading rules pic.setUrl(localPath.replace("\\", "/" ) + "static/ProjectImgs" + uri.replace("\\", "/") + "/" + newFileName + "." + suffix); // Insert into database // ... map.put( "resultStr" , pic.getUrl()); return map; } /** * Get the current date string * @param separator * @return */ public static String getNowDateStr(String separator){ Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); // remember to add one to month (because it counts from 0 by default) int month = now.get(Calendar.MONTH)+1 ; int day = now.get(Calendar.DATE); return year + separator + month + separator + day; } // Generate a unique file name public static String getUniqueFileName(){ String str = UUID.randomUUID().toString(); return str.replace("-", ""); } }
Picture
kind:
package com.xxx.bean; import java.util.Date; public class Picture { private String localPath; private String name; private String url; private Date addTime; public Picture() { } public Picture(String localPath, String name, String url, Date addTime) { this.localPath = localPath; this.name = name; this.url = url; this.addTime = addTime; } public String getLocalPath() { return localPath; } public void setLocalPath(String localPath) { this.localPath = localPath; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Date getAddTime() { return addTime; } public void setAddTime(Date addTime) { this.addTime = addTime; } }
In normal Web
development, the above general writing method can be adapted to your own project needs with a little modification. For example , you need to set various restrictions on uploading files in the SSM
framework ;dispatchServlet.xml
You SpringBoot
can .yml
configure the file path in the file and the Application
file size property in the class where the project starts.
The following is SpringBoot
the reference writing method of the configuration file size, which is written in the class ShouguoApplication
, that is, the entry program segment:
package com.xxx; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import javax.servlet.MultipartConfigElement; @SpringBootApplication public class ShouguoApplication { public static void main(String[] args) { SpringApplication.run(ShouguoApplication.class, args); } /** * File upload configuration */ @Bean public MultipartConfigElement multipartConfigElement(){ MultipartConfigFactory factory = new MultipartConfigFactory(); // maxSize factory.setMaxFileSize("10240KB" ); // Set the total upload data size factory.setMaxRequestSize("102400KB" ); return factory.createMultipartConfig(); } }