在使用ssm完成前后端对接时,总免不了前台传过来的文件问题,而html中的<input>框直接使用时,往往会获取不到路径,今天在完成图片上传后的来做个总结
首先,前台页面
1 <!DOCTYPE html> 2 <html> 3 ????<head> 4 ????????<meta charset="utf-8" /> 5 ????????<title>图片上传</title> 6 ????</head> 7 ????<body> 8 ????????<h2>图片上传</h2> 9 ????<form action="save/saveImg" method="post" enctype="multipart/form-data">10 ????????图片:<input type="file" ?name="upload"/><br/>11 ????????<input type="submit" value="提交"/>12 ????</form>13 ????</body>14 </html>
配置图片解析
1 <!-- 配置文件上传视图解析器 -->2 ????<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">3 ????????<property name="maxUploadSize" value="10485760"></property>4 ????????<property name="defaultEncoding" value="utf-8"></property>5 ????</bean>
其中 maxUploadSize 是限制上传的图片最大字节 defaultEncoding是设定上传图片编码
service接口
1 package com.sp.service;2 3 import org.springframework.web.multipart.MultipartFile;4 5 public interface FileService {6 7 ????void upLoadFile(MultipartFile upload);8 }
实现类
1 package com.sp.serviceImpl; 2 ?3 import java.io.File; 4 import java.io.IOException; 5 ?6 import org.springframework.stereotype.Service; 7 import org.springframework.web.multipart.MultipartFile; 8 ?9 import com.sp.service.FileService;10 11 @Service12 public class FileServiceImpl implements FileService {13 14 ????private String filePath="D:/img/"; //定义上传文件的存放位置15 ????@Override16 ????public void upLoadFile(MultipartFile upload) {17 ????????18 ????????String fileName = upload.getOriginalFilename(); ?//获取上传文件的名字19 ????????//判断文件夹是否存在,不存在则创建20 ????????File file=new File(filePath); 21 ????????22 ????????if(!file.exists()){23 ????????????file.mkdirs();24 ????????}25 ????????26 ????????String newFilePath=filePath+fileName; //新文件的路径27 ????????28 ????????try {29 ????????????upload.transferTo(new File(newFilePath)); ?//将传来的文件写入新建的文件30 ????????????31 ????????} catch (IllegalStateException | IOException e) {32 ????????????e.printStackTrace();33 ????????}34 35 ????}36 37 }
控制层
1 package com.sp.controller; 2 ?3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.ResponseBody; 7 import org.springframework.web.multipart.MultipartFile; 8 ?9 import com.sp.service.FileService;10 11 @Controller12 @RequestMapping("/save")13 public class FileController {14 15 ????@Autowired16 ????private FileService fileService;17 ????18 ????@RequestMapping("/saveImg")19 ????@ResponseBody20 ????public String saveImg(MultipartFile upload){21 ????????fileService.upLoadFile(upload);22 ????????return "ok";23 ????}24 }
效果演示
选择图片
提交后看我的d盘目录
本案例只是简单的演示,后台可以对上传的图片名称或者大小或者有无尺寸进行判断,从而可以避免传入无效数据,同时亦可以将自己所保存的路径进行相应的修改后存入数据库,便于以后数据的回显.
ssm实现图片上传
原文地址:https://www.cnblogs.com/xQlover/p/9898255.html