Java:使用唯一的名称重命名MultiPartFile并将其存储到文件夹中,然后将url保存到数据库中

Java:使用唯一的名称重命名MultiPartFile并将其存储到文件夹中,然后将url保存到数据库中,java,spring-boot,jakarta-ee,Java,Spring Boot,Jakarta Ee,我有一个基于Spring Boot的后端,一个基于Angular 5的前端。 通过Angular接收多部分文件后,我想用 唯一名称(表的id)并将文件存储到文件夹中,然后将此文件的URL放入数据库PostgreSQL。 请帮帮我,我测试了很多方法,但没有任何好结果。 我试图将多部分文件转换为多部分文件,但我不知道怎么做。 请帮帮我 以下是包含处理MultiPartFile的方法的类: 以下是RestController: 如果文件名只是个问题,那么代码很好,您只需要使用一些字符串创建文件名,或者

我有一个基于Spring Boot的后端,一个基于Angular 5的前端。 通过Angular接收多部分文件后,我想用 唯一名称(表的id)并将文件存储到文件夹中,然后将此文件的URL放入数据库PostgreSQL。 请帮帮我,我测试了很多方法,但没有任何好结果。 我试图将多部分文件转换为多部分文件,但我不知道怎么做。 请帮帮我

以下是包含处理MultiPartFile的方法的类: 以下是RestController:
如果文件名只是个问题,那么代码很好,您只需要使用一些字符串创建文件名,或者像下面那样清理文件名

//Create custom filename 
String filename = StringUtils.cleanPath(file.getOriginalFilename());
//remove spaces and make lowercase    
filename = filename.toLowerCase().replaceAll(" ", "-");

然后在你的复制方法中

Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
                StandardCopyOption.REPLACE_EXISTING); 
下面是一个例子

@Service
public class UploadService {

@Value("${app.image.cdn}")
private String imageCDN;

@Value("${app.upload.path}")
private String uploadPath;

private Path rootLocation;


public String store(MultipartFile file) {

    String storedLocation;
    rootLocation = Paths.get(uploadPath);

    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    filename = filename.toLowerCase().replaceAll(" ", "-");

    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + filename);
        }
        if (filename.contains("..")) {
            // This is a security check
            throw new StorageException(
                    "Cannot store file with relative path outside current directory "
                            + filename);
        }
        Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
                StandardCopyOption.REPLACE_EXISTING);

        storedLocation = imageCDN+filename;

    }
    catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }


    return storedLocation;
}
}
以及您的application.properties

spring.servlet.multipart.max-file-size=20MB
spring.servlet.multipart.max-request-size=20MB

app.upload.path=/uploads
app.image.cdn=http://yourhost.com/uploads/
还有你的StorageException类

public class StorageException extends RuntimeException {

  public StorageException(String message) {
    super(message);
  }

  public StorageException(String message, Throwable cause) {
    super(message, cause);
  }
}
这是RestController
其他类没有更改,包括前端。您当前的代码有什么问题?谢谢您的回答。在将多部分文件存储到文件夹之前,我想用Prestataires的唯一名称(表中行的id)id重命名多部分文件。然后将文件的URL保存到数据库中。类似于file.renameTo(String.valueOf(p.getId())的内容)。p是Prestataires的一个实例。@beyyatoabdellah-重命名是另一个选项。为什么不在第一个实例中创建正确的名称呢。检查更新的答案。我会尝试这个,我会告诉你结果。谢谢,先生。我在后端有此错误:smart.syndic.metier.StorageException:无法存储文件null.png,原因是:java.nio.file.NoSuchFileException:\uploads\null.png。我认为null的问题是文件被重命名为具有null的Prestataires的id,因为它将在respository.save(p)时刻生成;所以在这个操作之前它是空的。此外,我不希望只有一个文件夹用于保存文件,我希望有多个。是的,修复空id,对于多个目录,只需创建文件夹并相应地更改文件名。在postman中测试api时出现以下错误“未能转换类型为'org.springframework.web.multipart.support.StandardMultipartTTpServletRequest$StandardMultipartFile'的属性值。请帮助我修复此错误@beyyatoabdellah”
Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
                StandardCopyOption.REPLACE_EXISTING); 
@Service
public class UploadService {

@Value("${app.image.cdn}")
private String imageCDN;

@Value("${app.upload.path}")
private String uploadPath;

private Path rootLocation;


public String store(MultipartFile file) {

    String storedLocation;
    rootLocation = Paths.get(uploadPath);

    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    filename = filename.toLowerCase().replaceAll(" ", "-");

    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + filename);
        }
        if (filename.contains("..")) {
            // This is a security check
            throw new StorageException(
                    "Cannot store file with relative path outside current directory "
                            + filename);
        }
        Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
                StandardCopyOption.REPLACE_EXISTING);

        storedLocation = imageCDN+filename;

    }
    catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }


    return storedLocation;
}
}
spring.servlet.multipart.max-file-size=20MB
spring.servlet.multipart.max-request-size=20MB

app.upload.path=/uploads
app.image.cdn=http://yourhost.com/uploads/
public class StorageException extends RuntimeException {

  public StorageException(String message) {
    super(message);
  }

  public StorageException(String message, Throwable cause) {
    super(message, cause);
  }
}
package smart.syndic.web;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
 import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import smart.syndic.dao.PrestatairesRepository;
import smart.syndic.dao.PrestatairesTypesRepository;
import smart.syndic.entities.Prestataires;
import smart.syndic.metier.StorageService;

@RestController
@CrossOrigin("*")
public class PrestatairesRestController 
{
@Autowired
private PrestatairesRepository repository;

@Autowired
private PrestatairesTypesRepository repository2;

@Autowired
private StorageService storageService;

private List<String> files = new ArrayList<String>();

@RequestMapping(value="/prestataires/{id}", 
        method=RequestMethod.GET)
public Prestataires getVilles(@PathVariable Long id)
{
    return repository.findOne(id);
}

@RequestMapping(value="/prestataires", 
        method=RequestMethod.POST)
public Prestataires addVilles(Prestataires p,
        @RequestParam("multipartFile") MultipartFile file)
{
    Prestataires pp = null;
    try{
        pp = repository.save(p);
        storageService.store(file, "prestataires",pp);
        files.add(file.getOriginalFilename());


    }catch(Exception e){
        e.printStackTrace();
    }

    p.setPrestatairesTypes(repository2.findOne(p.getPrestatairesTypes().getId()));
    updateVilles(p.getId(), p);
    return pp;              
}

@RequestMapping(value="/prestataires/{id}", 
        method=RequestMethod.PUT)
public Prestataires updateVilles(
        @PathVariable Long id,
        @RequestBody Prestataires v)
{

    v.setId(id);
    return repository.save(v);
}
}
package smart.syndic.metier;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
 import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import smart.syndic.entities.Prestataires;

@Service
public class StorageService 
{
private String imageCDN = "http://www.yourHost.com/fichiers/";

private Path rootLocation;

public String store(MultipartFile file, String chemin, Prestataires p) {
    String storedLocation = null;
    rootLocation = Paths.get("fichiers/"+chemin+"/");
    String filename = null;

    filename = p.getId()+"."+file.getOriginalFilename()
    .substring(
            file.getOriginalFilename().lastIndexOf(".") + 1);


    try {
        if(file.isEmpty()){
            throw new StorageException("Failed to store Empty"
                    + " File "+filename);
        }
        if(filename.contains(".."))
        {
            throw new StorageException("Cannot store file with relative path "
                    + "outside current directory "+filename);
        }

        Files.copy(file.getInputStream(), this.rootLocation.resolve(filename), 
                StandardCopyOption.REPLACE_EXISTING);
        storedLocation = imageCDN + filename;
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }
    p.setPhoto("fichiers/"+chemin+"/"+filename);
    return storedLocation;
}

public Resource loadFile(String filename) {
    try {
        Path file = rootLocation.resolve(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new RuntimeException("FAIL!");
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException("FAIL!");
    }
}

public void deleteAll() {
    FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
}