Spring mvc 在文件系统而不是数据库上保存图像
我正在开发一个应用程序,用户可以在其中提供文本信息和图像。我想将图像保存在文件系统和数据库中,我会将每个用户的链接添加到其图像中,因此我需要将用户ID添加到图像名称中,以避免获得具有相同名称的图像。我正在使用SpringMVC。 在我的控制器中:Spring mvc 在文件系统而不是数据库上保存图像,spring-mvc,spring-boot,Spring Mvc,Spring Boot,我正在开发一个应用程序,用户可以在其中提供文本信息和图像。我想将图像保存在文件系统和数据库中,我会将每个用户的链接添加到其图像中,因此我需要将用户ID添加到图像名称中,以避免获得具有相同名称的图像。我正在使用SpringMVC。 在我的控制器中: @RequestMapping(value="/save",method=RequestMethod.POST) public String add ( @RequestParam("prix") Long prix,
@RequestMapping(value="/save",method=RequestMethod.POST)
public String add ( @RequestParam("prix") Long prix,
RequestParam("adresse") String ville,
@RequestParam("categorie") String categorie,
@RequestParam("photos") MultipartFile file,
) throws FileNotFoundException
{
String chemin=null;
if (!file.isEmpty())
{
try {
String orgName = file.getOriginalFilename();
// this line to retreive just file name
String
name=orgName.substring(orgName.lastIndexOf("\\")+1,orgName.length());
chemin="e:\\images\\"+name; //here I want to add id (auto generated)
File file1=new File(chemin);
file.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
}
}
annonce.setImage(chemin);
annonce.setTitre(prix);
annonce.setCorps(ville);
annonce.setPrix(cetegorie)
annoncedao.save(annonce);
return "SuccessAddAnnonce";
}
但是我无法获取自动生成的ID,所以我无法获取它,因为它是自动生成的,直到调用save method witch is last,我才拥有它。
欢迎您提供任何建议。您可以为每个用户生成一个随机ID,并将其分配给特定用户,因此其图像名称也是您在此处打算执行的操作 我将简单地加以说明
// Get a random ID coressponding to the user address or whatever, here i will just use address
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] hash = digest.digest(ville.getBytes("UTF-8"));
String randomId = DatatypeConverter.printHexBinary(hash);
// Here you have a uniqueID for an address.
// You could have just used ville.hashCode() also but it might give you collisions with some different Strings.
如果输入:64街,市中心,然后
randomId=8AB126F8EBC0F7B5CCBBEBB3E21582ADF我使用带有Select max Id的查询来获取Id @查询从ANNOCE中选择MAXid 长鳍一次递增
我希望能帮助别人。你想为一个用户生成一个随机ID吗?不,每次我添加一个用户时,都会生成一个ID,我想从数据库中获取最后一个ID。你没有告诉我它是哪个数据库,mysql?关于它的模式是什么,所以我可以帮忙对不起,是的,它是MySQL