# 引入 js

ajaxfileupload.js

# 异步上传文件

```javascript
$("body").on("change", "input[type=file]", function () {
    var fileElementId = $(this).attr("id");
    var data = {"key": fileElementId};

    $.ajaxFileUpload({
        url: '/ad/creative/upload',
        secureuri: false,
        data: data, //除了文件之外的其他数据
        fileElementId: fileElementId, //input元素的id
        dataType: 'json',
        success: function (result) {
            if (result['status'] == 1) {
                for (var key in result) {
                    if (key == 'status' || key == 'msg') {
                        continue;
                    }

                    $("#" + key).val(result[key]);
                }

                //预览、下载
                $('#' + fileElementId).parent().nextAll().remove();
                $('#' + fileElementId).parent().after('<a target="_blank" href="' + result[fileElementId + 'Path'] + '" title="预览" xmlns="http://www.w3.org/1999/html"><div class="iconAdvertiser auditMediaAd"></div></a><a id="download" href="javascript:void(0);" title="下载"><div class="iconAdvertiser downloadAd"></div></a>');
            } else {
                tooltip(data['msg']);
            }
        },
        error: function () {
            tooltip("生成模板失败!");
        }
    });
});
```

# Controller 相应方法

```java
@RequestMapping("upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file, @RequestParam("key") String key) {
    Map<String, Object> map = new HashMap<>();

    if (file == null || file.isEmpty()) {
        map.put("status", 0);
        map.put("msg", "请选择文件");
    } else {
        Map<String, String> fileMap = creativeService.uploadMaterial(file, key);

        if (fileMap != null) {
            map.put("status", 1);
            map.put("msg", "上传成功");
            map.putAll(fileMap);
        } else {
            map.put("status", 0);
            map.put("msg", "上传失败");
        }
    }

    return JSONObject.fromObject(map).toString();
}
```