jquery.fileupload 使用

1、页面部分
引入的样式、js

jquery.fileupload.css
jquery-1.8.2.min.js
jquery.ui.widget.js
jquery.fileupload.js

页面

<div class="btn btn-primary btn-sm fileinput-button" id="hide-button">
  <i class="glyphicon glyphicon-plus"></i>
  <span>上传</span>
  <input id="imageFile" type="file" name="imageFile">
</div>

绑定事件

$('#' + fileId).fileupload({
    url: '/upload/image?type=' + type,
    add: function (e, data) {
          var uploadErrors = [];
          var acceptFileTypes = /^image\/(png|jpe?g)$/i;
          //文件类型判断
          if (!acceptFileTypes.test(data.originalFiles[0]['type'])) {
             return false;
          }
         //文件大小判断
          if (data.originalFiles[0]['size'] > 5000 * 1024) {
               return false;
          }
          if (uploadErrors.length > 0) {
                    return false;
                } else {
                    data.submit();
                }
          },
          done: function (e, data) {
                ......
          }
 });

2、java部分

@RestController
@RequestMapping("/file")
public class FileController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${app.file.upload.server.origin}")
    private String origin;
    @Value("${app.file.upload.server.path}")
    private String realPath;
    @Value("${app.file.upload.dir.userPicture}")
    private String userPicturePath;
    @Value("${app.file.upload.size.max.image}")
    private int imageFileMaxSize;

    @PostMapping("/upload/image")
    public Result uploadImage(@RequestParam MultipartFile imageFile) {
        validateImageFile(imageFile);
        String dateDIR = DateFormatUtils.format(new Date(), "yyyyMMdd");
        String path = userPicturePath + dateDIR + "/";
        // 为上传的文件进行重命名(避免同名文件的相互覆盖)使用UUID + 文件后缀
        String suffix = imageFile.getOriginalFilename().substring(imageFile.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        File file = new File(realPath + path + fileName);
        if (!file.getParentFile().exists()) {
            file.mkdirs();
        }
        //将临时文件保存到磁盘
        try {
            imageFile.transferTo(file);
        } catch (IOException e) {
            logger.error("文件上传失败", e);
            throw new ServiceException("上传失败:" + e.getMessage());
        }
        Map<Object, Object> data = Maps.newLinkedHashMap();
        data.put("url", origin + path + fileName);
        return ResultGenerator.genSuccessResult(data);
    }

    private void validateImageFile(MultipartFile imageFile) throws ServiceException {
        //校验类型
        if (imageFile.getContentType().indexOf("image") == -1) {
            throw new ServiceException("上传失败,仅支持图片类型!");
        }
        if (imageFile.getSize() > (imageFileMaxSize * 1024 * 1024)) {
            throw new ServiceException("上传失败,文件大小不能超过" + imageFileMaxSize + "MB!");
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,738评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,633评论 19 139
  • 我们是流浪的船舶 家是温暖的港湾 无论走到哪儿 总有一丝牵挂 千萦万绕连到我们身上 也许未来的路还很长 或许充满了...
    荒野里的鬼阅读 1,592评论 0 6
  • 后来我活的利索随性潇洒 却始终学不会像你这样说走就走 你是我枯水年纪里的一场雨 你来的酣畅淋漓 我淋的一病不起 当...
    故梦j阅读 3,280评论 4 8