我所想要的图片上传接口是指服务器端在完成图片上传后,返回一个可访问的图片地址

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>

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

直接代码吧!

controller层

 @RequestMapping(value="/uploadImg", method=RequestMethod.POST)
@ResponseBody
public String uploadImg(@RequestParam(value="img")MultipartFile img, HttpServletResponse response){
JSONObject result = new JSONObject();
boolean flag = true;
try {
flag = pictureUploadService.upload(img, result);
} catch (Exception e) {
result.put("mess", "调用失败");
flag = false;
e.printStackTrace();
}
result.put("flag", flag); response.setContentType("text/html;charset=UTF-8");
//解决跨域名访问问题
response.setHeader("Access-Control-Allow-Origin", "*"); return result.toString();
}

service层

 /**
* 上传图片
* @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;
}

(暂时没有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("-", "");
    }

上传图片流程如下:

点击上传后,返回

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

springMVC框架下——通用接口之图片上传接口的更多相关文章

  1. Asp.NetCoreWebApi图片上传接口(二)集成IdentityServer4授权访问(附源码)

    写在前面 本文地址:http://www.cnblogs.com/yilezhu/p/9315644.html 作者:yilezhu 上一篇关于Asp.Net Core Web Api图片上传的文章使 ...

  2. (SSM框架)实现小程序图片上传(配小程序源码)

    阅读本文约"2分钟" 又是一个开源小组件啦! 因为刚好做到这个小功能,所以就整理了一下,针对微信小程序的图片(文件)上传! 原业务是针对用户反馈的图片上传.(没错,本次还提供小程序 ...

  3. springmvc上传图片并显示--支持多图片上传

    实现上传图片功能在Springmvc中很好实现.现在我将会展现完整例子. 开始需要在pom.xml加入几个jar,分别是: <dependency> <groupId>comm ...

  4. 用海豚框架(DolphinPHP)实现单/多图片上传时,如何获得图片路径

    用框架实现图片上传很简单,就不多说了,然后这个框架的实现机制是这样的,我们选择图片,点击上传,他会将图片保存在uploads下,以当天时间和随机字母作为图片名,然后在返回个数字,这个数字是这个图片的i ...

  5. SpringMVC框架(四)文件的上传下载,上下文路径

    文件目录: SpringMVC配置文件: <?xml version="1.0" encoding="UTF-8"?> <beans xmln ...

  6. vue下实现input实现图片上传,压缩,拼接以及旋转

    背景 作为一名前端工作人员,相信大家在开发系统的时候,经常有遇到需要这么一种需求,就是需要为用户保存上传的图片,很多小白遇到这个问题的时候,都会虎躯一震,以为会是一个棘手的问题,当你读完这篇文章的时候 ...

  7. layedit图片上传接口案列

    html部分 <divclass="layui-form-item"> <labelfor="tname"class="layui- ...

  8. thinkphp5图片上传接口

    public function avatarUpload() { $file = request()->file('file'); $filePath = 'avatar'; $width = ...

  9. 简单总结下关于blob的图片上传

    我是从一本书上看到了Azure Blob,然后在网上浪了一会儿,发现了这篇文章,里面他已经把重点的则重地方讲完了,"飞机票:http://www.cnblogs.com/sparkdev/p ...

随机推荐

  1. IE8上传文件时文件本地路径变成"C:\fakepath\"的问题

    转自:http://yunzhu.iteye.com/blog/1116893 在使用<input id="file_upl" type="file" / ...

  2. Python实践:开篇

    一.概述 Python实践 是应用Python解决实际问题的案例集合,这些案例中的Python应用通常 功能各异.大小不一. 该系列文章是本人应用Python的实践总结,会不定期更新. 二.目录 Py ...

  3. 5分钟上手写ECharts的第一个图表

    网址:http://echarts.baidu.com/doc/start.html 架构特性 http://echarts.baidu.com/doc/feature.html | 架构 提供商业产 ...

  4. LightOJ1031 Easy Game(区间DP)

    我可能真想不到这题是区间DP,不过知道是区间DP想了下就AC了. dp[i][j]表示局面为ai...aj先手能获得与后手得分的最大差值 那么转移到当前状态就是枚举中间的位置,分成两边,其中一边先手全 ...

  5. DataTable排序的一般方法

    一.重生法dstaset.Tables.Add(dt)dataset.Tables(0).DefaultView.Sort = "id desc" 二.直接法dv = New Da ...

  6. ccrendertexture to uiimage

    CCRenderTexture *renderTexture; [renderTexture getUIImage];

  7. C#SortedList排序列表怎么样逆序输出

    C#分别在集合库和泛型库中有共2套SortedList 以较新的泛型库为例,SortedList<int, string> l = new SortedList<int, strin ...

  8. 用LinqPad查看Nhibernate生成的sql语句

    使用Nhibernate开发一般都要对Nhibernate生成的sql语句进行查看及分析,查看Nhibernate生成的sql语句,可以使用NHProfiler和log4net.但NHProfiler ...

  9. Vim 学习资料

    VIM中文手册 简明 Vim 练级攻略 所需即所获:像 IDE 一样使用 vim

  10. css margin居中的问题

    1.要在外壳套上一个父div加上100%宽度,在子div加上宽度和margin:auto; 2.子div的宽度通常是子div中元素的宽度,比如子div中一个宽度为169px的input.想居中的话,就 ...