springmvc图片文件上传

用MultipartFile文件方式传输

Controller

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();
}
}

配置文件

No=TP
jpg=.jpg
picturePath=/picture/

偶遇晨光

2016-05-30

 

springmvc图片文件上传接口的更多相关文章

  1. SpringMvc MultipartFile 图片文件上传

    spring-servlet.xml <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipar ...

  2. SpringMVC+ajax文件上传实例教程

    原文地址:https://blog.csdn.net/weixin_41092717/article/details/81080152 文件上传文件上传是项目开发中最常见的功能.为了能上传文件,必须将 ...

  3. SpringMVC学习--文件上传

    简介 文件上传是web开发中常见的需求之一,springMVC将文件上传进行了集成,可以方便快捷的进行开发. springmvc中对多部件类型解析 在 页面form中提交enctype="m ...

  4. .Net Core 图片文件上传下载

    当下.Net Core项目可是如雨后春笋一般发展起来,作为.Net大军中的一员,我热忱地拥抱了.Net Core并且积极使用其进行业务的开发,我们先介绍下.Net Core项目下实现文件上传下载接口. ...

  5. springmvc实现文件上传

    springmvc实现文件上传 多数文件上传都是通过表单形式提交给后台服务器的,因此,要实现文件上传功能,就需要提供一个文件上传的表单,而该表单就要满足以下3个条件 (1)form表彰的method属 ...

  6. 【SpringMVC】SpringMVC 实现文件上传

    SpringMVC 实现文件上传 文章源码 文件上传回顾 查看 JavaWeb 阶段的文件上传下载 实现步骤: 客户端: 发送 post 请求,告诉服务器要上传什么文件 服务器: 要有一个 form ...

  7. Spring +SpringMVC 实现文件上传功能。。。

    要实现Spring +SpringMVC  实现文件上传功能. 第一步:下载 第二步: 新建一个web项目导入Spring 和SpringMVC的jar包(在MyEclipse里有自动生成spring ...

  8. SpringMVC之文件上传异常处理

    一般情况下,对上传的文件会进行大小的限制.如果超过指定大小时会抛出异常,一般会对异常进行捕获并友好的显示出来.以下用SpringMVC之文件上传进行完善. 首先配置CommonsMultipartRe ...

  9. jmeter测试文件上传接口报错:connection reset by peer: socket write error

    最近在对文件上传接口性能测试时,设置150线程数并发时,总会出现以下错误:connection reset by peer: socket write error 在网上搜索了一下,得到的原因有这些: ...

随机推荐

  1. rails使用bootstrap3-wysiwyg可视化编辑器并实现自定义图片上传插入功能

    之前在rails开发中使用了ckeditor作为可视化编辑器,不过感觉ckeditor过于庞大,有很多不需要的功能,而且图片上传功能不好控制不同用户可以互相删除图片,感觉很不好.于是考虑更改可视化编辑 ...

  2. [转]linux,windows 可执行文件(ELF、PE)

    ELF (Executable Linkable Format)UNIX类操作系统中普遍采用的目标文件格式 . 首先要知道它有什么作用:工具接口标准委员会TIS已经将ELF作为运行在Intel32位架 ...

  3. springMvc3.0.5搭建全程 (转)

    用了大半年的Spring MVC3.0,用着感觉不错.简单写一个搭建Spring MVC3.0的流程(以Spring3.0.5为列),数据库交互使用spring JDBC Template,附件有项目 ...

  4. kali linux 安装nvidia

    开始安装之前需要说明一下几点: 1.安装闭源显卡驱动有一定风险,比如黑屏或者无法进入图形界面什么的.如果您很害怕折腾,而且不在Linux系统中玩开源游戏(比如Nexuiz)或看高清电影,默认的nouv ...

  5. SpringMVC——文件上传

    ----------------------------------------------------------------------------spring.xml-------------- ...

  6. 随机梯度下降(Stochastic gradient descent)和 批量梯度下降(Batch gradient descent )的公式对比、实现对比[转]

    梯度下降(GD)是最小化风险函数.损失函数的一种常用方法,随机梯度下降和批量梯度下降是两种迭代求解思路,下面从公式和实现的角度对两者进行分析,如有哪个方面写的不对,希望网友纠正. 下面的h(x)是要拟 ...

  7. SQLServer 自增主键创建, 指定自增主键列值插入数据,插入主键

    http://blog.csdn.net/zh2qiang/article/details/5323981 SQLServer 中含自增主键的表,通常不能直接指定ID值插入,可以采用以下方法插入. 1 ...

  8. 扩展JQuery和JS的方法

    //JS的扩展方法: 1 定义类静态方法扩展 2 定义类对象方法扩展            var aClass = function(){} //1 定义这个类的静态方法            aC ...

  9. 在Ubuntu上安装LAMP服务器

    1.安装Ubuntu上安装LAMP apt-get install lamp-server^ 2.安装过程中设置MySql密码 3.测试 创建index.php var/www/html/index. ...

  10. [Linux] - CentOS IP设置方法

    CentOS 7的IP设置方法: 1.手动设置IP方法 a) 运行命令,cd到目录: cd /etc/sysconfig/network-scripts/ b) 运行命令:ls -l 找到类似这个文件 ...