无法使用MongoDb GridFs上传文件 [英] Could not Upload File using MongoDb GridFs

查看:275
本文介绍了无法使用MongoDb GridFs上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring-Boot的新手,我试图将文件上传到Mongodb数据库,保存其objectId并将其链接到我的文档,以便以后下载. 这是我班的人:

I'm new to Spring-Boot,i'm trying to upload file to Mongodb Database, save its objectId and link it to my document, in order to download it Later. Here is my class Person:

@Document
public class Person {
@Id
private String id;

private String firstName;
private String lastName;
private String age;
private String filename;
private ObjectId file;
 ....}

这是我的控制器方法:

@RequestMapping(value="/addperson",method=RequestMethod.POST)
public String ajout(Model model,@Valid PersonForm pf){

    Person p=new Person(pf.getFirstname(),pf.getLastName(),pf.getAge());
    InputStream inputStream=null;
    try {
        inputStream = new FileInputStream("E:/usb/");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    p.setFilename(pf.getFilename());
    repository.linkFileToMyDoc(p,inputStream,p.getFilename());
    repository.save(p);
    model.addAttribute("PersonForm",pf);
    return "personview";
}

我想知道这是否是最好的方法. 我得到的错误是对"E:/usb/"的访问被拒绝. 谁能帮忙

I wonder if it is the best method to do it. the error i get is that access to "E:/usb/" is denied. Can anyone help please

推荐答案

在阅读MultipartFile文档后,我找到了解决方案.我将文件上传到服务器,然后将其完全控制到目录"E:/usb/",然后将其传输到目录.这是我的控制器方法:

i found the solution after reading MultipartFile documentation. I uploaded file to server and then transfered it to directory,after allowing total control to directory "E:/usb/". this is my controller method:

   Person p=new Person(pf.getFirstname(),pf.getLastName(),pf.getAge());


    try {
        File dest = null;
        String str = "C:/tt/"+pf.getFile().getOriginalFilename();
        File dir = new File(str);
        dir.createNewFile();
        pf.getFile().transferTo(dir);
        p.setFilename(str);
        InputStream inputStream=pf.getFile().getInputStream();
         repository.linkFileToMyDoc(p,inputStream,pf.getFile().getOriginalFilename());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    repository.save(p);
    model.addAttribute("PersonForm",pf);
    return "personview";
}

linkFileToMydoc方法,您可以在以下链接中找到它: 如何使用@DbRef注释来引用GridFSFile(春季数据mongodb )

the linkFileToMydoc method, you'll find it in this link: How to reference GridFSFile with @DbRef annotation (spring data mongodb)

这篇关于无法使用MongoDb GridFs上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆