java实现MultipartFile多文件上传并用;拼接地址

java实现MultipartFile多文件上传并用;拼接地址,第1张

java实现MultipartFile多文件上传并用;拼接地址
    @Value("${upload.url}")
    private String url;
    public static  final   List list = Arrays.asList("jpg", "png","jpeg","JPEG","JPG","PNG");
    public String getImgPaths(MultipartFile[] uploadFile) {
        String filePaths= "";
        for (MultipartFile file : uploadFile) {
                String oldName = file.getOriginalFilename();
                String fileType = oldName.substring(oldName.lastIndexOf(".") + 1);
                if (!list.contains(fileType)){
                    throw new BizException("201","图片格式只能为jpg或png");
                }
                String format = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
                File directory=new File(url+format);
                if (!directory.exists()){
                    directory.mkdirs();
                }
                //1、给上传的图片生成新的文件名
                String  newName = UUID.randomUUID().toString().replaceAll("-","") + oldName.substring(oldName.lastIndexOf("."));
                try {
                    file.transferTo(new File(directory,newName));
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("图片上传失败", e);
                }
                    if (Objects.equals("",filePaths)){
                        filePaths= format+"/"+newName;
                    }else {
                        filePaths+=";"+format+"/"+newName;
                    }
        }
        return  filePaths;
    }

地址要访问的话需要做映射(或者用nginx)

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Value("${upload.url}")
    private String url;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        //windows本地文件目录
        registry.addResourceHandler("/**").addResourceLocations("file:"+url);
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5715652.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存