首页 > 代码库 > springMVC图片上传的处理方式

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:;" 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 = http://www.mamicode.com/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="http://www.mamicode.com/‘ + result + ‘"/></div>‘);
        } else {
            alert("请上传.jpg、.png、.gif格式的图片!");
        }
    }).fail(function () {
        alert("图片上传失败!");
    });
});

 后端接收:

   @RequestMapping(value = "http://www.mamicode.com/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;
    }

 

springMVC图片上传的处理方式