文件上传入门案例
页面剖析
<form action="http://localhost:8091/file" method="post" enctype="multipart/form-data"> <input name="fileImage" type="file" /> <input type="submit" value="提交"/> </form>
编辑FileController
@RestControllerpublic class FileController { /** * 文件上传的入门案例 * url:http://localhost:8091/file * 参数: fileImage 名称 * 返回值: 文件上传胜利!!! * SpringMVC 提供了工具API 专门操作流文件. * * 文件上传的具体步骤: * 1.筹备文件目录 * 2.筹备文件的全名 xxxx.jpg * 3.筹备文件上传的门路 D:/JT-SOFT/images/xxxx.jpg * 4.将字节信息输入即可. * 大小不要超过1M */ @RequestMapping("/file") public String file(MultipartFile fileImage) throws IOException { String dirPath = "D:/JT-SOFT/images"; File dirFile = new File(dirPath); if(!dirFile.exists()){ dirFile.mkdirs(); //一劳永逸的写法 } //获取文件的名称 String fileName = fileImage.getOriginalFilename(); //获取文件全门路 String filePath = dirPath + "/" + fileName; File file = new File(filePath); fileImage.transferTo(file); //将字节信息输入到指定的地位中 return "文件上传胜利!!!!"; }}
商品文件上传实现
页面剖析
筹备ImageVO对象
@Data@Accessors(chain = true)@NoArgsConstructor@AllArgsConstructorpublic class ImageVO { //{"error":0,"url":"图片的保留门路","width":图片的宽度,"height":图片的高度} private Integer error; //错误信息 0程序运行失常 1.文件上传有误. private String url; //图片拜访的虚构门路 private Integer width; // >0 private Integer height; // >0 //设定上传失败的办法 public static ImageVO fail(){ return new ImageVO(1,null,null,null); } public static ImageVO success(String url,Integer width,Integer height){ return new ImageVO(0,url,width,height); }}
编辑FileController
/** * 实现文件上传 * url地址: http://localhost:8091/pic/upload?dir=image * 参数: uploadFile: 文件的字节信息. * 返回值: {"error":0,"url":"图片的保留门路","width":图片的宽度,"height":图片的高度} * ImageVO对象... */ @RequestMapping("/pic/upload") public ImageVO upload(MultipartFile uploadFile){ return fileService.upload(uploadFile); }
编辑FileService
@Servicepublic class FileServiceImpl implements FileService{ private String rootDirPath = "D:/JT-SOFT/images"; //1.2 筹备图片的汇合 蕴含了所有的图片类型. private static Set<String> imageTypeSet; static { imageTypeSet = new HashSet<>(); imageTypeSet.add(".jpg"); imageTypeSet.add(".png"); imageTypeSet.add(".gif"); } /** * 欠缺的校验的过程 * 1. 校验是否为图片 * 2. 校验是否为恶意程序 * 3. 避免文件数量太多,分目录存储. * 4. 避免文件重名 * 5. 实现文件上传. * @param uploadFile * @return */ @Override public ImageVO upload(MultipartFile uploadFile) { //1.校验图片类型 jpg|png|gif..JPG|PNG.... //1.1 获取以后图片的名称 之后截取其中的类型. abc.jpg String fileName = uploadFile.getOriginalFilename(); int index = fileName.lastIndexOf("."); String fileType = fileName.substring(index); //将数据转化为小写 fileType = fileType.toLowerCase(); //1.3 判断图片类型是否正确. if(!imageTypeSet.contains(fileType)){ //图片类型不匹配 return ImageVO.fail(); } //2.校验是否为恶意程序 依据宽度/高度进行判断 try { //2.1 利用工具API对象 读取字节信息.获取图片对象类型 BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream()); //2.2 校验是否有宽度和高度 int width = bufferedImage.getWidth(); int height = bufferedImage.getHeight(); if(width==0 || height==0){ return ImageVO.fail(); } //3.分目录存储 yyyy/MM/dd 分隔 //3.1 将工夫依照指定的格局要求 转化为字符串. String dateDir = new SimpleDateFormat("/yyyy/MM/dd/") .format(new Date()); //3.2 拼接文件存储的目录对象 String fileDirPath = rootDirPath + dateDir; File dirFile = new File(fileDirPath); //3.3 动态创建目录 if(!dirFile.exists()){ dirFile.mkdirs(); } //4.避免文件重名 uuid.jpg 动静拼接 //4.1 动静生成uuid 实现文件名称拼接 名.后缀 String uuid = UUID.randomUUID().toString().replace("-", ""); String realFileName = uuid + fileType; //5 实现文件上传 //5.1 拼接文件实在门路 dir/文件名称. String realFilePath = fileDirPath + realFileName; //5.2 封装对象 实现上传 File realFile = new File(realFilePath); uploadFile.transferTo(realFile); //实现文件上传胜利!!!! String url = "https://img14.360buyimg.com/n0/jfs/t1/45882/22/7027/53284/5d49358aE9c25c1bd/fb7365463f6a1a7b.jpg"; return ImageVO.success(url,width,height); } catch (IOException e) { e.printStackTrace(); return ImageVO.fail(); } }}
页面成果展示
文件上传优化
url优化
阐明:如果须要通过网络虚构门路拜访服务器,则应该依照如下的配置实现
- 本地磁盘门路: D:JT-SOFTimages20200930a.jpg
- 网络虚构门路: http://image.jt.com20200930a.jpg
编辑pro配置文件
实现属性的动静赋值
@Service@PropertySource("classpath:/properties/images.properties")//容器动静的加载指定的配置文件public class FileServiceImpl implements FileService{ //因为属性的值前期可能会发生变化,所以应该动静的获取属性数据, // 利用pro配置文件@Value("") @Value("${image.rootDirPath}") private String rootDirPath;//="E:/log";//定义文件的根目录 @Value("${image.urlPath}") private String urlPath;//="http://image.jt.com";//定义虚构门路前缀 //1.2筹备图片的汇合,蕴含了所有的图片类型 //因为汇合中的图片名不能反复,所以用set汇合 //如果写在办法里比拟繁琐,所以用动态代码块封装图片汇合 private static Set<String> imageTypeSet; static{ imageTypeSet=new HashSet<>(); imageTypeSet.add(".jpg"); imageTypeSet.add(".png"); imageTypeSet.add(".gif"); } /** * 欠缺的校验的过程 * 1.校验是否为图片 * 2.校验是否为恶意程序 * 3.为了避免文件数量太多,分目录讯处 * 4.避免文件重名 * * 实现文件上传 * @param uploadFile * @return */ @Override public ImageVO upload(MultipartFile uploadFile) { //避免有多余空格,所以先做去除空格的解决 rootDirPath.trim(); urlPath.trim(); //1.校验图片类型 jpg/png/gif/... // 1.1先获取图片名,之后截取其中的类型 String fileName=uploadFile.getOriginalFilename(); int index=fileName.lastIndexOf(".");//截取“.”当前的内容 String fileType=fileName.substring(index);//取得类型:.jpg //1.2筹备图片的汇合,蕴含了所有的图片类型 //因为汇合中的图片名不能反复,所以用set汇合 //如果写在办法里比拟繁琐,所以用动态代码块封装图片汇合 //避免文件名后缀大小写问题,将所有的数据转化为小写 fileType=fileType.toLowerCase(); //1.3 判断图片类型是否正确 //contains(fileType)示意一个元素是否属于这个汇合 if(!imageTypeSet.contains(fileType)){ //图片类型不匹配 return ImageVO.fail(); } //2.校验程序是否为恶意程序 依据宽度和高度进行判断 //2.1利用工具api对象 读取字节信息,获取图片对象类型 try { BufferedImage bufferedImage=ImageIO.read(uploadFile.getInputStream()); //2.2校验是否有宽度和高度 int width=bufferedImage.getWidth(); int height=bufferedImage.getHeight(); if(width==0||height==0){ return ImageVO.fail(); } //3.分目录存储 依据工夫 yyyy/MM/dd 分隔 //3.1将工夫依照指定的格局要求转化为字符串 String dateDir=new SimpleDateFormat("/yyyy/MM/dd/") .format(new Date()); //3.2拼接文件存储的目录对象 String fileDirPath=rootDirPath+dateDir; File dirFile=new File(fileDirPath); //3.3动态创建目录 if(!dirFile.exists()){ dirFile.mkdirs(); } //4.避免文件重名 uuid.jpg动静拼接 //4.1动静生成uuid 实现文件名称拼接 名.后缀 String uuid= UUID.randomUUID().toString().replace("-", ""); String realFileName=uuid+fileType; //5.实现文件上传 //5.1拼接文件真是门路 dir/文件名称 String realFilePath=fileDirPath+realFileName; //5.2封装对象 File realFile=new File(realFilePath); //5.3实现上传 uploadFile.transferTo(realFile); //实现文件上传胜利 //设置图片的虚构门路 String url=urlPath+dateDir+realFileName; return ImageVO.success(url,width,height); }catch(Exception e){ e.printStackTrace(); return ImageVO.fail(); } }}