亲宝软件园·资讯

展开

springMVC图片上传的处理方式 springMVC图片上传的处理方式详解

dali_lyc 人气:0
想了解springMVC图片上传的处理方式详解的相关内容吗,dali_lyc在本文为您仔细讲解springMVC图片上传的处理方式的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:springMVC,图片上传,下面大家一起来学习吧。

首先需要依赖的jar包:

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>1.3.2</version>
</dependency>
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.2.1</version>
</dependency>

页面:

<a href="javascript:;" rel="external nofollow" class="a-upload">
  <input class="" type="file" name="file" id="file" required="required">上传
</a>

大家如果觉得默认的上传文件的按钮不好看,可以引入下面的css样式:

.a-upload {
 padding: 4px 10px;
 height: 27px;
 line-height: 27px;
 position: relative;
 cursor: pointer;
 color: #888;
 background: #fafafa;
 border: 1px solid #ddd;
 border-radius: 4px;
 overflow: hidden;
}
.a-upload input {
 position: absolute;
 width: 100%;
 right: 0;
 top: 0;
 opacity: 0;
 filter: alpha(opacity=0);
 cursor: pointer
}
.a-upload:hover {
 color: #444;
 background: #eee;
 border-color: #ccc;
 text-decoration: none
}

前端脚本:

$('#file').on('change', function () {
 var $this = $(this);
 var formData = new FormData();
 formData.append('file', $('#file')[0].files[0]);
 var fileName = $('#file')[0].files[0].name;
 var fileType = fileName.substring(fileName.lastIndexOf('.') + 1);
 var fileSize = $('#file')[0].files[0].size;
 if (fileType != 'jpg' && fileType != 'png' && fileType != 'gif') {
  alert("请上传.jpg、.png、.gif格式的图片!");
  return;
 }
 if (fileSize > 300 * 1024) {
  alert("请上传大小小于300KB的图片!");
  return;
 }
 $.ajax({
  url: '/admin/upload',
  type: 'POST',
  data: formData,
  cache: false,
  processData: false,
  contentType: false
 }).done(function (result) {
  if (result != '') {
   $this.closest('div').append('<div class="img-preview"><img src="' + result + '"/></div>');
  } else {
   alert("请上传.jpg、.png、.gif格式的图片!");
  }
 }).fail(function () {
  alert("图片上传失败!");
 });
});

后端接收:

 @RequestMapping(value = "admin/upload", method = RequestMethod.POST)
 @ResponseBody
 public String uploadFile(@RequestParam("file") MultipartFile file) {
  try {
   String filename = file.getOriginalFilename();
   if (filename.endsWith("jpg") || filename.endsWith("png") || filename.endsWith("gif")) {
    String prefix = filename.substring(filename.lastIndexOf("."));
    String imgName = UUID.randomUUID().toString() + prefix;
    String imgUri = writeToFileSystem(imgName, file.getBytes());
    return imgUri;
   }
  } catch (Exception e) {
   LOG.error("uploadFile failed:", e);
  }
  return null;
 }

加载全部内容

相关教程
猜你喜欢
用户评论