Search in sources :

Example 1 with Attach

use of com.tale.model.entity.Attach in project tale by otale.

the class IndexController method upload.

/**
 * 上传文件接口
 */
@SysLog("上传附件")
@PostRoute("api/attach/upload")
@JSON
public RestResponse<?> upload(Request request) {
    log.info("UPLOAD DIR = {}", TaleUtils.UP_DIR);
    Users users = this.user();
    Integer uid = users.getUid();
    List<Attach> errorFiles = new ArrayList<>();
    List<Attach> urls = new ArrayList<>();
    Map<String, FileItem> fileItems = request.fileItems();
    if (null == fileItems || fileItems.size() == 0) {
        return RestResponse.fail("请选择文件上传");
    }
    fileItems.forEach((fileName, fileItem) -> {
        String fname = fileItem.getFileName();
        if ((fileItem.getLength() / 1024) <= TaleConst.MAX_FILE_SIZE) {
            String fkey = TaleUtils.getFileKey(fname);
            String ftype = fileItem.getContentType().contains("image") ? Types.IMAGE : Types.FILE;
            String filePath = TaleUtils.UP_DIR + fkey;
            try {
                Files.write(Paths.get(filePath), fileItem.getData());
                if (TaleUtils.isImage(new File(filePath))) {
                    String newFileName = TaleUtils.getFileName(fkey);
                    String thumbnailFilePath = TaleUtils.UP_DIR + fkey.replace(newFileName, "thumbnail_" + newFileName);
                    ImageUtils.cutCenterImage(CLASSPATH + fkey, thumbnailFilePath, 270, 380);
                }
            } catch (IOException e) {
                log.error("", e);
            }
            Attach attach = new Attach();
            attach.setFname(fname);
            attach.setAuthorId(uid);
            attach.setFkey(fkey);
            attach.setFtype(ftype);
            attach.setCreated(DateKit.nowUnix());
            attach.save();
            urls.add(attach);
            siteService.cleanCache(Types.SYS_STATISTICS);
        } else {
            Attach attach = new Attach();
            attach.setFname(fname);
            errorFiles.add(attach);
        }
    });
    if (errorFiles.size() > 0) {
        return RestResponse.fail().payload(errorFiles);
    }
    return RestResponse.ok(urls);
}
Also used : FileItem(com.blade.mvc.multipart.FileItem) Attach(com.tale.model.entity.Attach) ArrayList(java.util.ArrayList) Users(com.tale.model.entity.Users) IOException(java.io.IOException) File(java.io.File) PostRoute(com.blade.mvc.annotation.PostRoute) SysLog(com.tale.annotation.SysLog) JSON(com.blade.mvc.annotation.JSON)

Aggregations

JSON (com.blade.mvc.annotation.JSON)1 PostRoute (com.blade.mvc.annotation.PostRoute)1 FileItem (com.blade.mvc.multipart.FileItem)1 SysLog (com.tale.annotation.SysLog)1 Attach (com.tale.model.entity.Attach)1 Users (com.tale.model.entity.Users)1 File (java.io.File)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1