多图片上传技术(后端)
今天学了个SSM多图片上传,来记录一下
1.查询前端指定的url(/pic/upload),上传文件参数名称(uploadFile)
2.要求的返回值
//成功时
{
"error" : 0,
"url" : "http://www.example.com/path/to/file.ext"
}
//失败时
{
"error" : 1,
"message" : "错误信息"
}
3.创建FTP配置文件
#FTP相关配置
#FTP的IP地址
FTP_ADDRESS=(ip)
FTP_PORT=21
FTP_USERNAME=ftpuser
FTP_PASSWORD=密码
FTP_BASE_PATH=/home/ftpuser/img
#图片服务器的相关配置
#图片服务器的基础url
IMAGE_BASE_URL=http://(ip)/img
4.修改 dao层扫描注解的功能来读取上面配置文件
<!-- 加载配置文件 加载resource下的db.properties-->
<context:property-placeholder location="classpath:resource/*.properties" />
5.在springmvc.xml中添加多图片上传功能的配置
<!-- 定义文件上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
6.编写service层(@Value注解读取配置文件的属性)
功能:接收controller层传递过来的图片对象,把图片上传到ftp服务器。给图片生成一个新的名字。
import java.util.HashMap;
import java.util.Map;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.taotao.common.utils.FtpUtil;
import com.taotao.common.utils.IDUtils;
import com.taotao.service.PictureService;
//图片上传服务
@Service
public class PictureServiceImpl implements PictureService {
//从配置文件中取出指定字段的值赋给下面,下面不是必须的,可以自己选择叫什么
@Value("${FTP_ADDRESS}")
private String FTP_ADDRESS;
@Value("${FTP_PORT}")
private Integer FTP_PORT;
@Value("${FTP_USERNAME}")
private String FTP_USERNAME;
@Value("${FTP_PASSWORD}")
private String FTP_PASSWORD;
@Value("${FTP_BASE_PATH}")
private String FTP_BASE_PATH;
@Value("${IMAGE_BASE_URL}")
private String IMAGE_BASE_URL;
@Override
public Map uploadPicture(MultipartFile uploadFile){
HashMap resultMap = new HashMap<>();
try {
//取原文件名
String oldName = uploadFile.getOriginalFilename();
//生成新文件名
//UUID newName = UUID.randomUUID();//这是其中一种方法
String newName = IDUtils.genImageName();
//合成新的图片名
newName = newName + oldName.substring(oldName.lastIndexOf("."));
//图片上传
DateTime dateTime = new DateTime();
String imagePath = dateTime.toString("/yyyy/MM/dd");//设置文件路径格式以日期上传
boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH
,imagePath, newName, uploadFile.getInputStream());
//返回结果
if (!result){
resultMap.put("error",1);
resultMap.put("massage","文件上传失败");
return resultMap;
}
resultMap.put("error", 0);
resultMap.put("url", IMAGE_BASE_URL + imagePath + "/" +newName);
return resultMap;
} catch (Exception e) {
resultMap.put("error", 1);
resultMap.put("message", "文件上传发生异常");
return resultMap;
}
}
}
其中用的到IDUtils工具类如下
//图片id生成
public static String genImageName() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上三位随机数
Random random = new Random();
int end3 = random.nextInt(999);
//如果不足三位前面补0
String str = millis + String.format("%03d", end3);
return str;
}
//商品id生成
public static long genItemId() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上两位随机数
Random random = new Random();
int end2 = random.nextInt(99);
//如果不足两位前面补0
String str = millis + String.format("%02d", end2);
long id = new Long(str);
return id;
}
7.controller层
功能:接收页面传递过来的图片。调用service上传到图片服务器。返回结果。
@Autowired
private PictureService pictureService;
@RequestMapping("/pic/upload")
@ResponseBody
public String pictureUpload(MultipartFile uploadFile){
Map result = pictureService.uploadPicture(uploadFile);
//为了保持功能的兼容性,需要把Result转换成json格式
String json = JsonUtils.objectToJson(result);
return json;
}