您的位置:首页 > 编程语言 > Java开发

springMVC框架下——通用接口之图片上传接口

2016-01-24 23:24 621 查看
  我所想要的图片上传接口是指服务器端在完成图片上传后,返回一个可访问的图片地址

spring mvc框架下图片上传非常简单,如下 

@RequestMapping(value="/uploadImg", method=RequestMethod.POST)
@ResponseBody
public String uploadImg(@RequestParam(value="img")MultipartFile img){
File f = new File("/data/images");
try{
FileUtils.copyInputStreamToFile(img.getInputStream(), f);
}catch(Exception e){
e.printStackTrace();
}
return "上传成功";
}


非常简单吧!

<form action="http://localhost/component/common/uploadImg" method="post" enctype="multipart/form-data">
头像:<input type="file" name="img" /><br/>
<input type="image" src="./images/img_submit.gif" />
</form>


以上仅仅只是能够上传文件而已,而我们还要能返回一个图片地址,这个图片地址要能在浏览器中直接访问,如下:

/**
* 上传图片
* @param file
* @param params
* @return
* @throws Exception
*/
public boolean upload(MultipartFile file, JSONObject params) throws Exception{
//过滤合法的文件类型
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
String allowSuffixs = "gif,jpg,jpeg,bmp,png,ico";
if(allowSuffixs.indexOf(suffix) == -1){
params.put("resultStr", "not support the file type!");
return false;
}

//获取网络地址、本地地址头部
Properties config = new Properties();
config.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
String urlPath = config.getProperty("urlRoot");
String localPath = config.getProperty("localRoot");

//创建新目录
String uri = File.separator + DateUtil.getNowDateStr(File.separator);
File dir = new File(localPath + uri);
if(!dir.exists()){
dir.mkdirs();
}

//创建新文件
String newFileName = StringUtil.getUniqueFileName();
File f = new File(dir.getPath() + File.separator + newFileName + "." + suffix);

//将输入流中的数据复制到新文件
FileUtils.copyInputStreamToFile(file.getInputStream(), f);

//创建Picture对象
Picture pic = new Picture();
pic.setLocalPath(f.getAbsolutePath());
pic.setName(f.getName());
pic.setUrl(urlPath + uri.replace("\\", "/") + "/" + newFileName + "." + suffix);
pic.setAddTime(new Date());

//插入到数据库
//...

params.put("resultStr", pic.getUrl());

return true;
}


View Code
(暂时没有dao层,我在properties中配置网络地址的域名以及本地文件存储目录)

上传文件有几个地方需要注意:

上传文件的中文乱码(这个暂不考虑,毕竟要实现的是图片上传)

限制上传文件大小(文件过大,会导致服务器不堪重负),这个我们在spring mvc的配置文件中进行限制

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="defaultEncoding" value="utf-8" />
<beans:property name="maxUploadSize" value="10485760000" />
<beans:property name="maxInMemorySize" value="40960" />
</beans:bean>


限制上传文件类型(这个我们在service层进行处理)

如果一个文件夹下面保存超过1000个文件,就会影响文件访问性能,所以上传的文件要分散存储(这个分散策略有多种,不必拘泥于一种。我这里偷懒用了年月日作为目录层级

/**
* 获取当前日期字符串
* @param separator
* @return
*/
public static String getNowDateStr(String separator){
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH)+1;
int day = now.get(Calendar.DATE);

return year + separator + month + separator + day;
}


上传成功后保存的文件不能重名(即文件名要唯一)

//生成唯一的文件名
public static String getUniqueFileName(){
String str = UUID.randomUUID().toString();
return str.replace("-", "");
}


上传图片流程如下:



点击上传后,返回



在浏览器中输入上面的这个图片地址访问,然后出现

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: