All Downloads are FREE. Search and download functionalities are using the official Maven repository.

site.zfei.at.file.FileUploadController Maven / Gradle / Ivy

package site.zfei.at.file;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import site.zfei.at.coxt.Result;
import site.zfei.at.coxt.StsException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping(value = "/at/file")
public class FileUploadController {


    @Resource
    private AtFileConfigurationProperties properties;

    @Resource
    private AtTraceConfigurationProperties traceConfigurationProperties;

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file, HttpServletRequest request) {

        File folder = new File(System.getProperty("user.dir") + properties.getUploadPath());
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名,避免文件重名
        String oldName = file.getOriginalFilename();
        if (oldName == null) {
            oldName = "default";
        }
        String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            String ipUrl = Optional.ofNullable(traceConfigurationProperties.getServerHost()).orElse(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort());
            String url = ipUrl + request.getContextPath() + properties.getVisitPath() + "/" + newName;
            return Result.of(url);
        } catch (IOException e) {
            throw new StsException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy