当前位置: 移动技术网 > IT编程>开发语言>Java > SpringMVC文件上传及查看的示例代码

SpringMVC文件上传及查看的示例代码

2019年07月19日  | 移动技术网IT编程  | 我要评论

写在前面

谈到文件上传,首先要说业务逻辑,如果上传的文件大家都可以看(比如广告或者首页的banner)等,那么我们就把图片放在静态资源区(与css,js一样的位置)中,如果文件是受保护的(像用户只能查看自己上传的照片),那么我们就把它存放在服务器中的某个专门存放图片的位置。

本例分别展示了存放在两个位置的上传文件的方法,上传之后,作为延伸,还添加了查看上传的文件以及下载已经上传的文件的功能。

准备工作

配置springmvc,导入commons包

在mvc-servlet.xml中配置文件上传解析器

<!--文件上传解析器-->
 <bean id="multipartresolver"
  class="org.springframework.web.multipart.commons.commonsmultipartresolver">
  <property name="maxuploadsize" value="1000000"/>
  <property name="defaultencoding" value="utf-8" />
 </bean>

存放在静态资源区

1、存放位置:

存放在项目中,所以路径为相对项目的路径。

/{yourproject}/webapp/static/img

2、配置响应的handler

@controller
public class uploadcontroller {
 @getmapping("/upload")
 public string uploadhandler() {
 return "upload";
 }

 @postmapping("/upload/static")
 public void writostatic(httpservletrequest request,
       redirectattributes redirectattributes,
       @requestparam("filename") multipartfile file) {
 if(!file.isempty()) {
  //获取目标文件夹
  string path = request.getservletcontext().getrealpath("/") + "static/img/";
  //获取用户上传的源文件名
  string filename = file.getoriginalfilename();
  //新建文件
  file file1 = new file(path, filename);
  //将文件写入
  file.transferto(file1);

  redirectattributes.addflashattribute("message","upload to static success");
  return "redirect:/upload";
 } else {
  redirectattributes.addflashattribute("message","upload file can not be empty");
  return "redirect:/upload";
 }

 }
}

存放在服务器

1、本例存放位置:

存放在服务器某个位置,与项目无关,所以地址为绝对路径。

/users/mac/desktop/imgtemp/, 为目录的绝对路径。

2、配置响应的handler

...
@postmapping("/upload/disk")
public string writetodisk(httpservletrequest request,
       @requestparam("filename") multipartfile file,
       redirectattributes redirectattributes) {
 if(!file.isempty()) {
 //获取源文件名
 string filename = file.getoriginalfilename();
 //获取保存文件文件夹路径
 string path = "/users/mac/desktop/imgtemp/";
 //新建文件
 file file1 = new file(path,filename);
 //写入文件
 file.transferto(file1);
 }

}
...

延伸部分(文件的查看及下载)

由于响应是要以流的形式传递文件,我们需要正确的设置响应的mimie类型才能被浏览器正确的解析,应用程序文件的默认mimie类型为 application/octet-stream,mime设置为该值后,浏览器不会自动执行或询问执行这类文件,会以对待附件的形式直接将文件下载至本地。

更多关于mimie的解读请查看这篇文章

如果我们如果想自定义下载文件的名字,那么就需要设置content-disposition消息。
content-disposition 消息头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地。

更过关于content-disposition的解读请查看这篇文章

...
@getmapping("/download/bydefault")
public void getimgbydefault(@requestparam string filename,
       @requestparam(required=false,defaultvalue="") string savename),
       httpservletresponse response {
 if(stringutils.isempty(filename)) {
  response.senderror(404);
  return;
 }
 //文件存放的路径
 string path = "/users/mac/desktop/imgtemp/";
 //新建文件
 file file = new file(path,filename);

 if(!file.exists()) {
  response.senderror(404);
  return;
 }
 //如果请求参数savename不为空,进行文件的下载
 if(!stringutils.isempty(savename)) {
  //设置响应长度
  response.setcontentlength((int)file.length());
  //设置响应的mime类型为application/octet-stream
  response.setcontenttype(mediatype.application_octet_stream_value);

  savename = new string(savename.getbytes("utf-8"),"iso8859-1");
  //设置content-disposition为attachment;filename=savename
  response.setheader(httpheaders.content_disposition, "attachment; filename=\""+savename+"\"");
 }
 //读取文件
 inputstream is = new fileinputstream(file);
 outputstream os = response.getoutputstream();
 //将文件以流的形式输出
 ioutils.copy(is,os);
 os.flush();
 os.close();
 is.close();

}

我们还可以使用springmvc自带的 bytearrayhttpmessageconverter 转化器来将文件输出,该转换器实现 httpmessageconverter 接口。可读取所有mime的请求信息,响应信息的mime为 application/octet-stream

...
@getmapping("/download/byconvert")
public httpentity<byte[]> getimgbyconvert(@requestparam string filename,
           @requestparam(required=false,defaultvalue="") string savename) {
 if(stringutils.isempty(filename)) {
  return new responseentity<>(httpstatus.not_found);
 }

 string path = "/users/mac/desktop/imgtemp/";
 file file = new file(path,filename);

 if(!file.exists()) {
  return new responseentity<>(httpstatus.not_found);
 }

 httpheaders headers = new httpheaders();
 if(!stringutils.isempty(savename)) {
  headers.setcontenttype(mediatype.application_octet_stream_value);
  headers.setcontentlength(file.length());

  savename = new sting(savename.getbytes("utf-8"),"iso8859-1");
  headers.add(httpheaders.content_disposition,"attachment;filename=\"" + savename + "\"");
 } else {
  headers.setcontenttype(mediatype.image_png);
 }

 return new httpentity<>(filecopyutils.copytobytearray(file),headers);

}

upload.jsp

<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport"
   content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 <meta http-equiv="x-ua-compatible" content="ie=edge">
 <title>document</title>
 <link rel="stylesheet" href="/static/bootstrap-3.3.5-dist/css/bootstrap.css" rel="external nofollow" >
</head>
<body>
<div class="container">
 <h1 class="text-center">上传文件撒</h1>
 <c:if test="${not empty message}">
  <h2>${message}</h2>
 </c:if>


 <form:form enctype="multipart/form-data" action="/upload/static">
  <p class="text-info">上传至/web/static</p>
  <label for="">上传文件:</label>
  <input type="file" name="uploadfile">

  <button class="btn btn-default">提交</button>
 </form:form>



 <form:form enctype="multipart/form-data" action="/upload/disk">
  <p class="text-info">上传至disk</p>
  <label for="">上传文件</label>
  <input type="file" name="uploadfile">

  <button class="btn btn-default">提交</button>
 </form:form>

 <div class="container">
  <button class="btn btn-default">
   <a href="/download/bydefault?filename=dubbo.png" rel="external nofollow" target="_blank">使用默认方式查看上传至disk的dubbo图片</a>
  </button>
  <button class="btn btn-default">
   <a href="/download/bydefault?filename=dubbo.png&savename=dubb.png" rel="external nofollow" >使用默认方式下载dubbo图片</a>
  </button>
 </div>

 <div class="container">
  <button class="btn btn-default">
   <a href="/download/byconvert?filename=dubbo.png" rel="external nofollow" target="_blank">使用mvc转化器查看上传至disk的dubbo图片</a>
  </button>
  <button class="btn btn-default">
   <a href="/download/byconvert?filename=dubbo.png&savename=dub.png" rel="external nofollow" >使用mvc转化器下载上传至disk的dubbo图片</a>
  </button>

 </div>
</div>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网