上传的文件一般保存在哪里_用rust写的一个应用,上传文件,保存文件,浏览文件...

讲解:

使用者通过curl工具上传文件。

aa010218716870017c56ece69320c6c9.png

文件的内容是:

echo 文件内容

得到:

一个url地址

在浏览器打开地址,可以浏览文件。

在upload文件夹,可以看到存储的文件,文件名为uNT,2K1,如图。

f13676120bf0e88bcfbbddbab440d750.png

rust代码怎么写呢?

才能实现这样的功能呢?

使用rocket

使用rust

依赖库:rocket,rand

代码有2个文件,

1个main.rs

调用一个模块文件

paste_id.rs

在main.rs里面使用paste_id文件里面的东西。

mod paste_id;

main.rs内容

#![feature(proc_macro_hygiene,decl_macro)]
#[macro_use]extern crate rocket;


use std::io;
use std::path::Path;
use rocket::Data;
use rocket::http::RawStr;

use std::fs::File;

mod paste_id; // file paste_id.rs 
use paste_id::PasteId;// in paste_id.rs ,it is a struct






#[get("/")]
fn index()->&'static str {
    "
       USAGE
            POST /
               accepts raw data in the body of the request and responds with  a URL of
               a page containing the body's content
            GET /<id>
               retrieves the content for the paste with id '<id>'
    "

}


#[post("/",data="<paste>")]
fn upload(paste:Data)->Result<String,std::io::Error>{

    let id=PasteId::new(8);//
    let filename=format!("upload/{id}",id=id);
    let url=format!("{host}/{id}n",host="http://localhost:8000",id=id);
    paste.stream_to_file(Path::new(&filename))?;
    Ok(url)
}


#[get("/<id>")]
fn retrieve(id:PasteId)->Option<File>{
        let filename=format!("upload/{id}",id=id);
        File::open(&filename).ok()
}

fn main() {
    rocket::ignite().mount("/",routes![index,upload,retrieve]).launch();
}

paste_id.rs内容

use std::fmt;
use std::borrow::Cow;

use rand::{self,Rng};
use rocket::http::RawStr;

use rocket::request::FromParam;


///Table to retrieve base62 values from
const BASE62:&[u8]=b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

///A _probably _unique paste ID

pub struct PasteId<'a>(Cow<'a,str>);

/// Returns 'true' if 'id' is a valid paste ID 'false' otherwise

fn valid_id(id:&str)->bool{
    id.chars().all(|c| {
    (c>='a' && c<='z')
    || (c>='A' && c<='Z')
    || (c>='0' && c<='9')
})

}

///Returns an instance of
///
impl <'a>FromParam<'a> for PasteId<'a>{
    type Error= & 'a RawStr;
    fn from_param(param:&'a RawStr)->Result<PasteId<'a>,&'a RawStr>{
        match valid_id(param){
            true =>Ok(PasteId(Cow::Borrowed(param))),
           false=>Err(param)
}

}}



impl<'a>PasteId<'a>{

    ///Generate
    /// the
   ///probability
   ///of IDs

    pub fn new(size:usize)->PasteId<'static>{

         let mut id=String::with_capacity(size);
         let mut rng=rand::thread_rng();
        for _  in 0..size {
             id.push(BASE62[rng.gen::<usize>() % 62] as char);
        }
       PasteId(Cow::Owned(id))
    }
}
impl <'a>fmt::Display for PasteId<'a>{
    fn fmt(&self,f:&mut fmt::Formatter)->fmt::Result {

            write!(f,"{}",self.0)
}
}

upload文件夹放在和src同一级

d3d0aefa4318b94ee50050b3371bfb6e.png

代码参考官方文档资料。学习参考。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值