在web-actix框架上实现上传文件
注意,文件会因为报文大小限制的问题而不得不把文件分为以大小最大为16384( 2 14 2^{14} 214)B大小为单位的报文,所以应先创建文件,再逐一添加数据。
// use...
const SAVE_DIR:&str = "/root";
//...
fn save_file_create(
name:String
){
let filepath = std::path::Path::new(SAVE_DIR).join(name);
std::fs::File::create(&filepath);
}
fn save_file_add(
name:String,
file:web::Bytes
)->Result<(), std::io::Error>{
let filepath = std::path::Path::new(SAVE_DIR).join(name);
let mut f = std::fs::OpenOptions::new().append(true).open(&filepath).unwrap();
f.write_all(&file)
}
#[post("/upload/{name}")]
async fn upload_file(
name: actix_web::web::Path<String>,
mut payload: actix_multipart::Multipart
) -> Result<actix_web::HttpResponse, Error> {
save_file_create(name.to_string());
// iterate over multipart stream
while let Some(item) = payload.next().await {
let mut field = item?;
// Field in turn is stream of *Bytes* object
while let Some(chunk) = field.next().await {
let data = chunk.unwrap();
save_file_add(name.to_string(),data).unwrap();
}
}
Ok(actix_web::HttpResponse::Ok().into())
}
// ...
其对应的js内容也比较简单
// ...
// <input type="file" id="upload_file" multiple/>
var files = document.getElementById("upload_file").files;
for(var i = 0 ;i<files.length;i++){
var formData = new FormData();
formData.append(files[i])
fetch(url, {
method: 'POST',
body:formData
})
}
// ...