springmvc文件上传代码
来源:互联网 发布:一朝得道天下知 编辑:程序博客网 时间:2024/06/03 12:13
package com.controller;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.service.PictureService;
import com.utils.PictureUtils;
import com.entity.JsonResult;
import com.entity.SimpleJsonResult;
@Controller
public class PictureController {
private static final Logger logger = Logger.getLogger(PictureController.class);
@Resource
private PictureService service;
@Value("#{settings['picturePath']}")
private String PATH;
/**
*
* 图片文件上传接口
*
* @param files
* 上传的文件图片数组
* @param childPath
* 子路径
* */
@RequestMapping(value = "baseSave", method = RequestMethod.POST)
@ResponseBody
public JsonResult save(@RequestParam(value = "file", required = false) MultipartFile[] files, String childPath) {
SimpleJsonResult result = new SimpleJsonResult(); // 自定义的一个输出类
if (files == null || files.length == 0) {
return result.setExecption("失败");
}
for (MultipartFile file : files) {
if (file.isEmpty())
return result.setExecption("失败");
try {
if (ImageIO.read(file.getInputStream()) == null)
return result.setExecption(EXECPTION_0041);
} catch (IOException e) {
logger.error("图片文件读取失败");
}
}
String name;
int size = 0;
List<String> url = new ArrayList<>();
String paths = PATH;
if (StringUtils.isNotBlank(childPath)) {
if (childPath.equals(PictureUtils.HELPS) || childPath.equals(PictureUtils.NEWS)) {
paths = paths + childPath + File.separator;
File filePath = new File(paths);
if (!filePath.exists())
filePath.mkdirs();
}
}
for (MultipartFile file : files) {
try {
name = service.save(file, paths);
size++;
url.add(name);
} catch (IOException e) {
logger.error(e, e);
return "失败";
}
}
return SimpleJsonResult.buildSuccessResult(url).setModel("number", size);
}
@PostConstruct
public void init() {
File file = new File(PATH);
file.setWritable(true, false);
if (!file.exists())
file.mkdirs();
if (!file.canWrite()) {
logger.error(file.getAbsolutePath() + ":文件夹没有权限创建");
return;
}
logger.info("filePath:" + PATH);
}
}
复制代码
SimpleJsonResult 类格式
复制代码
//SimpleJsonResult 类格式
/** public static SimpleJsonResult buildFailedSimpleJsonResult(IExceptionCode code) {
SimpleJsonResult result = new SimpleJsonResult();
result.setSuccess(false);
result.setMessage(code.getDescribe());
result.setCode(code.getCode());
return result;
}
public static SimpleJsonResult buildSuccessSimpleJsonResult(IExceptionCode code) {
SimpleJsonResult result = new SimpleJsonResult();
result.setSuccess(true);
result.setMessage(code.getDescribe());
result.setCode(code.getCode());
return result;
}
public static SimpleJsonResult build() {
SimpleJsonResult result = new SimpleJsonResult();
return result;
}
public SimpleJsonResult setExecption(IExceptionCode code) {
if (code.getCode().equals("0"))
setSuccess(true);
else
setSuccess(false);
this.code = code.getCode();
setMessage(code.getDescribe());
return this;
};
*/
复制代码
service类实现
复制代码
package com.service;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.entity.Picture;
import com.mappers.PictureMapper;
import com.utils.PictureUtils;
@Service
public class PictureService {
@Resource
private PictureMapper mapper;
private String no = "TP";
@Transactional(timeout = 3000)
public String save(MultipartFile file, String path) throws IOException {
//Picture width and height
BufferedImage bff =ImageIO.read(file.getInputStream());
Picture entity = new Picture(); //实体类
String fileName = file.getOriginalFilename();
String name = this.getName(fileName, file.getSize());
name = PictureUtils.save(file, path, name); //图片保存到服务器地址中
entity.setOriginal(fileName); // 上传的名称
entity.setName(name); // 名称
entity.setWidth(bff.getWidth()); // 宽
entity.setHeight(bff.getHeight()); //高
mapper.insert(entity); //添加进去
return name;
}
private String getName(String fileName, long size) { //重命名
StringBuilder sb = new StringBuilder();
String[] split = fileName.split("\\.");
String suffix = split[split.length - 1];
sb.append(fileName).append(System.currentTimeMillis()).append(new Random().nextFloat())
.append(Thread.currentThread().getId());
String name = DigestUtils.md2Hex(sb.toString()).toUpperCase();
return sb.delete(0, sb.length()).append(no).append(name).append(".").append(suffix).toString();
}
}
复制代码
PictureUtils 图片保存工具类
复制代码
package com.utils;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import net.coobird.thumbnailator.Thumbnails;
public class PictureUtils {
public static long SIZE = 100L << 10;
public static String SUFFIX_JPG = "jpg";
public static String NEWS = "news";
public static String HELPS = "helps";
//保存图片
public static String save(MultipartFile file, String path, String name) throws IOException {
int i = 1;
long size = file.getSize();
Thumbnails.of(file.getInputStream()).scale(1).outputQuality(1f)
.toFile(path + i + "_" + name);
if (size > SIZE) {
float ratio = 1.0f / (float) (size / SIZE);
++i;
Thumbnails.of(file.getInputStream()).scale(1).outputQuality(ratio)
.toFile(path + i + "_" + name);
}
return i + "_" + name;
}
// 设置宽高保存
public static String save(MultipartFile file, String path, String name, int width, int heigth, boolean compresseion)
throws IOException {
int i = 1;
long size = file.getSize();
Thumbnails.of(file.getInputStream()).size(width, heigth).outputQuality(1f)
.toFile(path + i + "_" + name);
if (size > SIZE) {
float ratio = 1f / (float) (size / SIZE);
++i;
Thumbnails.of(file.getInputStream()).size(width, heigth).outputQuality(ratio)
.toFile(path + i + "_" + name);
}
return i + "_" + name;
}
}
复制代码
实体类
复制代码
package com.entity;
public class Picture {
private static final long serialVersionUID = 1L;
@Column
private String original;
@Column
private String name;
@Column
private Integer width;
@Column
private Integer height;
public Picture() {
super();
}
}
//SimpleJsonResult 类格式
/** public static SimpleJsonResult buildFailedSimpleJsonResult(IExceptionCode code) {
SimpleJsonResult result = new SimpleJsonResult();
result.setSuccess(false);
result.setMessage(code.getDescribe());
result.setCode(code.getCode());
return result;
}
public static SimpleJsonResult buildSuccessSimpleJsonResult(IExceptionCode code) {
SimpleJsonResult result = new SimpleJsonResult();
result.setSuccess(true);
result.setMessage(code.getDescribe());
result.setCode(code.getCode());
return result;
}
public static SimpleJsonResult build() {
SimpleJsonResult result = new SimpleJsonResult();
return result;
}
public SimpleJsonResult setExecption(IExceptionCode code) {
if (code.getCode().equals("0"))
setSuccess(true);
else
setSuccess(false);
this.code = code.getCode();
setMessage(code.getDescribe());
return this;
};
复制代码
配置文件
No=TP
jpg=.jpg
picturePath=/picture/
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.service.PictureService;
import com.utils.PictureUtils;
import com.entity.JsonResult;
import com.entity.SimpleJsonResult;
@Controller
public class PictureController {
private static final Logger logger = Logger.getLogger(PictureController.class);
@Resource
private PictureService service;
@Value("#{settings['picturePath']}")
private String PATH;
/**
*
* 图片文件上传接口
*
* @param files
* 上传的文件图片数组
* @param childPath
* 子路径
* */
@RequestMapping(value = "baseSave", method = RequestMethod.POST)
@ResponseBody
public JsonResult save(@RequestParam(value = "file", required = false) MultipartFile[] files, String childPath) {
SimpleJsonResult result = new SimpleJsonResult(); // 自定义的一个输出类
if (files == null || files.length == 0) {
return result.setExecption("失败");
}
for (MultipartFile file : files) {
if (file.isEmpty())
return result.setExecption("失败");
try {
if (ImageIO.read(file.getInputStream()) == null)
return result.setExecption(EXECPTION_0041);
} catch (IOException e) {
logger.error("图片文件读取失败");
}
}
String name;
int size = 0;
List<String> url = new ArrayList<>();
String paths = PATH;
if (StringUtils.isNotBlank(childPath)) {
if (childPath.equals(PictureUtils.HELPS) || childPath.equals(PictureUtils.NEWS)) {
paths = paths + childPath + File.separator;
File filePath = new File(paths);
if (!filePath.exists())
filePath.mkdirs();
}
}
for (MultipartFile file : files) {
try {
name = service.save(file, paths);
size++;
url.add(name);
} catch (IOException e) {
logger.error(e, e);
return "失败";
}
}
return SimpleJsonResult.buildSuccessResult(url).setModel("number", size);
}
@PostConstruct
public void init() {
File file = new File(PATH);
file.setWritable(true, false);
if (!file.exists())
file.mkdirs();
if (!file.canWrite()) {
logger.error(file.getAbsolutePath() + ":文件夹没有权限创建");
return;
}
logger.info("filePath:" + PATH);
}
}
复制代码
SimpleJsonResult 类格式
复制代码
//SimpleJsonResult 类格式
/** public static SimpleJsonResult buildFailedSimpleJsonResult(IExceptionCode code) {
SimpleJsonResult result = new SimpleJsonResult();
result.setSuccess(false);
result.setMessage(code.getDescribe());
result.setCode(code.getCode());
return result;
}
public static SimpleJsonResult buildSuccessSimpleJsonResult(IExceptionCode code) {
SimpleJsonResult result = new SimpleJsonResult();
result.setSuccess(true);
result.setMessage(code.getDescribe());
result.setCode(code.getCode());
return result;
}
public static SimpleJsonResult build() {
SimpleJsonResult result = new SimpleJsonResult();
return result;
}
public SimpleJsonResult setExecption(IExceptionCode code) {
if (code.getCode().equals("0"))
setSuccess(true);
else
setSuccess(false);
this.code = code.getCode();
setMessage(code.getDescribe());
return this;
};
*/
复制代码
service类实现
复制代码
package com.service;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.entity.Picture;
import com.mappers.PictureMapper;
import com.utils.PictureUtils;
@Service
public class PictureService {
@Resource
private PictureMapper mapper;
private String no = "TP";
@Transactional(timeout = 3000)
public String save(MultipartFile file, String path) throws IOException {
//Picture width and height
BufferedImage bff =ImageIO.read(file.getInputStream());
Picture entity = new Picture(); //实体类
String fileName = file.getOriginalFilename();
String name = this.getName(fileName, file.getSize());
name = PictureUtils.save(file, path, name); //图片保存到服务器地址中
entity.setOriginal(fileName); // 上传的名称
entity.setName(name); // 名称
entity.setWidth(bff.getWidth()); // 宽
entity.setHeight(bff.getHeight()); //高
mapper.insert(entity); //添加进去
return name;
}
private String getName(String fileName, long size) { //重命名
StringBuilder sb = new StringBuilder();
String[] split = fileName.split("\\.");
String suffix = split[split.length - 1];
sb.append(fileName).append(System.currentTimeMillis()).append(new Random().nextFloat())
.append(Thread.currentThread().getId());
String name = DigestUtils.md2Hex(sb.toString()).toUpperCase();
return sb.delete(0, sb.length()).append(no).append(name).append(".").append(suffix).toString();
}
}
复制代码
PictureUtils 图片保存工具类
复制代码
package com.utils;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import net.coobird.thumbnailator.Thumbnails;
public class PictureUtils {
public static long SIZE = 100L << 10;
public static String SUFFIX_JPG = "jpg";
public static String NEWS = "news";
public static String HELPS = "helps";
//保存图片
public static String save(MultipartFile file, String path, String name) throws IOException {
int i = 1;
long size = file.getSize();
Thumbnails.of(file.getInputStream()).scale(1).outputQuality(1f)
.toFile(path + i + "_" + name);
if (size > SIZE) {
float ratio = 1.0f / (float) (size / SIZE);
++i;
Thumbnails.of(file.getInputStream()).scale(1).outputQuality(ratio)
.toFile(path + i + "_" + name);
}
return i + "_" + name;
}
// 设置宽高保存
public static String save(MultipartFile file, String path, String name, int width, int heigth, boolean compresseion)
throws IOException {
int i = 1;
long size = file.getSize();
Thumbnails.of(file.getInputStream()).size(width, heigth).outputQuality(1f)
.toFile(path + i + "_" + name);
if (size > SIZE) {
float ratio = 1f / (float) (size / SIZE);
++i;
Thumbnails.of(file.getInputStream()).size(width, heigth).outputQuality(ratio)
.toFile(path + i + "_" + name);
}
return i + "_" + name;
}
}
复制代码
实体类
复制代码
package com.entity;
public class Picture {
private static final long serialVersionUID = 1L;
@Column
private String original;
@Column
private String name;
@Column
private Integer width;
@Column
private Integer height;
public Picture() {
super();
}
}
//SimpleJsonResult 类格式
/** public static SimpleJsonResult buildFailedSimpleJsonResult(IExceptionCode code) {
SimpleJsonResult result = new SimpleJsonResult();
result.setSuccess(false);
result.setMessage(code.getDescribe());
result.setCode(code.getCode());
return result;
}
public static SimpleJsonResult buildSuccessSimpleJsonResult(IExceptionCode code) {
SimpleJsonResult result = new SimpleJsonResult();
result.setSuccess(true);
result.setMessage(code.getDescribe());
result.setCode(code.getCode());
return result;
}
public static SimpleJsonResult build() {
SimpleJsonResult result = new SimpleJsonResult();
return result;
}
public SimpleJsonResult setExecption(IExceptionCode code) {
if (code.getCode().equals("0"))
setSuccess(true);
else
setSuccess(false);
this.code = code.getCode();
setMessage(code.getDescribe());
return this;
};
复制代码
配置文件
No=TP
jpg=.jpg
picturePath=/picture/
0 0
- springmvc文件上传代码
- SpringMVC上传文件的简单代码实例
- SpringMVC上传图片代码
- (转)springmvc 文件下载上传典型代码
- SpringMVC 上传文件(超简单-5行代码)
- springMVC(11) springMVC文件上传
- SpringMVC-----8、SpringMVC上传文件
- springmvc文件上传总结
- SpringMVC multipart文件上传
- SpringMVC中的文件上传
- springmvc的文件上传
- springMVC上传文件
- springMVC 文件上传
- SpringMVC - 文件上传篇
- springMVC文件上传
- springMVC文件上传
- springMVC文件上传
- SpringMVC 上传文件
- 双链表的建立、测长、打印、删除、插入
- Java反射入门
- JSPatch OC->JS学习(1)
- window下的wamp散装
- ECharts 自定义动态tooltip
- springmvc文件上传代码
- 高精度小数
- java权限设计大纲
- ubuntu16.04 没有/var/log/messages
- 内部类访问局部变量的时候,为什么变量必须加上final修饰(转)
- java Date时间格式工具类DateUtil
- iOS 优化UITableView的性能
- 颜色选择器
- PL/SQL中SQL window和Command window有什么区别??