当前位置: 首页 > 知识库问答 >
问题:

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

微生鸿轩
2023-03-14

通过Angular收到MultiPartFile后,我想用唯一的名称(表的id)重命名这个文件,并将文件存储到文件夹中,然后把这个文件的URL到DataBase PostgreSQL.请帮帮我,我测试了很多方法没有任何好的结果。我试图将MultiPart File转换为File,但我不知道如何做。请帮帮我

package smart.syndic.metier;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

@Service
public class StorageService 
{
Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private final Path rootLocation = Paths.get("fichiers/prestataires");

public void store(MultipartFile file) {
    try {

        Files.copy(file.getInputStream(), 
this.rootLocation.resolve(file.getOriginalFilename()), 
StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception e) {
        throw new RuntimeException("FAIL!");
    }
 }

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());
 }
}
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)
{
    try{
        storageService.store(file);
        files.add(file.getOriginalFilename());
        p.setPhoto("fichiers/prestataires/"+file.getOriginalFilename());

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


 p.setPrestatairesTypes(repository2.findOne(p.getPrestatairesTypes()
 .getId()));

    return repository.save(p);              
}

}
package smart.syndic.entities;

import java.io.Serializable;
import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

@Entity
public class Prestataires implements Serializable 
{
@Id @GeneratedValue
private Long id;
private String nom;
private String email;
private String tele;
private String fax;
private String rib;
private String adresse;
private String taches;
private String photo;

//-------------------Constructors--------------------
//-------------------Getters and Setters--------------------


@ManyToOne
@JoinColumn(name="ID_PRESTATAIRES_TYPES")
private PrestatairesTypes prestatairesTypes;
}

共有2个答案

松英叡
2023-03-14
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());
}
}
江嘉悦
2023-03-14

如果文件名只是个问题,那么你的代码就可以了,你只需要用一些字符串创建文件名,或者像下面那样清理它

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

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

然后在你的复制方法中

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);
  }
}
 类似资料:
  • 事实上,我有一个标准,我必须上传一个产品图片到一个文件夹,图片名称,图片路径,产品名称和产品类型到mongoDb。通过将MultiPartFile作为@RequestParam传递,我已经成功地将图像从一个endpoint(/uploadFile)上传到了一个特定的文件夹中。我写了另一个enpoint来上传产品细节。但我无法将图像名称和图像路径获取到此endpoint(/uploadPath)。任

  • 我正在制作一个soundboard应用程序,当长按按钮1时,我需要共享sound1。我可以用以下代码创建共享菜单: 我可以与whatsapp和Google Drive完美共享音频文件,但其他应用程序不起作用。我听说您必须将文件复制到外部存储,并从那里共享它们。我已经搜索了将近两天,但我找不到这样做的方法。Stack上的其他文章也帮不了我:/ 如何在外部存储器中创建目录,将文件(sound1.ogg

  • 我的应用程序将一些文件保存到设备上的数据/数据文件夹中。保存远程文件后,我会处理这些文件,并将它们复制到其他文件夹中。在之前测试过的所有设备上,All都能正常工作,但在galaxy s3上会生成空指针异常。似乎我不被允许在那个文件夹上写或处理文件!但只有新的星系s3!我也无法使用EclipseDDMS文件浏览器在数据文件夹中找到任何文件,而在模拟器(相同的android版本)中,我可以正确查看所有

  • 我正在编写一个文件编写器,它将ID和名称(这两个字符串)写入文本文件。这需要用户输入,然后将数据存储在txt文件中。但是,当我再次运行它时,任何新数据都会覆盖以前的数据,因此数据永远不会保存到txt文件中。 谁能告诉我如何保存这些数据,以便添加的任何新数据都存储在下一行,而不覆盖上一行? 谢啦

  • 问题内容: 有人可以告诉我,在以下情况下如何进行? 接收文件(MS文件,ODS,PDF) 通过Apache Tika提取公元核心元数据+通过jackrabbit-content-extractors提取内容 使用Jackrabbit将文档(内容)及其元数据存储到存储库中 ? 检索文档+元数据 我对第3点和第4点感兴趣… 详细信息:该应用程序正在以交互方式处理文档(一些分析-语言检测,单词计数等。+

  • 问题内容: 我看到过很多不同的文章,涉及到您应该以何种方式将对象序列化到文件,并且所有这些在本质上在执行方式和最佳实践方面存在冲突。因此,这就是我要保存的内容: 我们可以假设configArgs的大小已知,我需要制作一个文件,这就是到目前为止的内容。 问题答案: 好吧,我想,您想将对象直接写入文件 我只是提供了重要的代码。通过异常处理来实现。