讲解:
使用者通过curl工具上传文件。
文件的内容是:
echo 文件内容
得到:
一个url地址
在浏览器打开地址,可以浏览文件。
在upload文件夹,可以看到存储的文件,文件名为uNT,2K1,如图。
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同一级
代码参考官方文档资料。学习参考。