如何将上传的文件保存到文件夹?

问题描述 投票:0回答:1

使用此功能,我通过 graphql 接收文件,如何将接收到的内容保存到文件夹中?

async fn single_upload(&self, ctx: &Context<'_>, file: Upload) -> FileInfo {
    let mut storage = ctx.data_unchecked::<FileStorage>().lock().await;
    println!("files count: {}", storage.len());
    let entry = storage.vacant_entry();
    let upload = file.value(ctx).unwrap();
    let info = FileInfo {
        id: entry.key().into(),
        filename: upload.filename.clone(),
        mimetype: upload.content_type,
    };

    entry.insert(info.clone());
    info
}

我正在使用 async-graphql 和 actix-web

rust graphql actix-web
1个回答
0
投票

在上面的代码中,您执行

let upload = file.value(ctx).unwrap();
,它获取
UploadValue
类型的实例。

/// A file upload value.
pub struct UploadValue {
    /// The name of the file.
    pub filename: String,
    /// The content type of the file.
    pub content_type: Option<String>,
    /// The file data.
    #[cfg(feature = "tempfile")]
    pub content: std::fs::File,
    /// The file data.
    #[cfg(not(feature = "tempfile"))]
    pub content: bytes::Bytes,
}

因此,如果

tempfile
功能打开,您可以将
content
文件复制到所需的文件夹(请参阅std::fs::copy)。否则,创建一个新文件,然后自己放入
content
字节(请参阅 std::io::copy)。

© www.soinside.com 2019 - 2024. All rights reserved.