微信小程序+SpringBoot使用HuTool实现文件上传

119 阅读1分钟
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.shr.core.Vo.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;

/**
 * 通用公共控制器
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${file.absolutePath}")
    private String ABSOLUTE_PATH;

    /**
     * 上传图片
     */
    @RequestMapping(value = "/imageUpload", method = RequestMethod.POST)
    public R pictureUpload(MultipartFile file) {
        File filePath = new File(ABSOLUTE_PATH);
        //判断这个路径是否存在,如果不存在创建这个路径
        if (!filePath.isDirectory()) {
            filePath.mkdir();
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String fileName = IdUtil.simpleUUID() + substring;
        // 目标文件
        File tofile = new File(filePath, fileName);
        try(OutputStream os = new FileOutputStream(tofile);){
            IoUtil.write(os, true, file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success("上传成功", fileName);
    }
}