标签:
extern crate multipart; extern crate iron; //Test Image And ImageHash extern crate image; extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use image::GenericImage; use std::fs::File; use std::io::Read; use std::path::Path; use multipart::server::{Multipart, Entries, SaveResult}; use iron::prelude::*; use iron::status; fn main() { Iron::new(process_request).http("localhost:8080").expect("Could not bind localhost:8080"); } /// Processes a request and returns response or an occured error. fn process_request(request: &mut Request) -> IronResult<Response> { // Getting a multipart reader wrapper match Multipart::from_request(request) { Ok(mut multipart) => { // Fetching all data and processing it. // save_all() reads the request fully, parsing all fields and saving all files // in a new temporary directory under the OS temporary directory. match multipart.save_all() { SaveResult::Full(entries) => process_entries(entries), SaveResult::Partial(entries, error) => { try!(process_entries(entries)); Err(IronError::new(error, status::InternalServerError)) } SaveResult::Error(error) => Err(IronError::new(error, status::InternalServerError)), } } Err(_) => { Ok(Response::with((status::BadRequest, "The request is not multipart"))) } } } /// Processes saved entries from multipart request. /// Returns an OK response or an error. fn process_entries(entries: Entries) -> IronResult<Response> { for (name, field) in entries.fields { println!(r#"Field "{}": "{}""#, name, field); } for (name, savedfile) in entries.files { let filename = match savedfile.filename { Some(s) => s, None => "None".into(), }; let mut file = match File::open(savedfile.path) { Ok(file) => file, Err(error) => { return Err(IronError::new(error, (status::InternalServerError, "Server couldn‘t save file"))) } }; //caculate md5 let mut buffer = Vec::new(); // read the whole file file.read_to_end(&mut buffer).unwrap(); let mut hasher = Md5::new(); hasher.input(&buffer); let md5 = hasher.result_str(); println!("{}", md5); //txt file // Write the contents of this image to the Writer in PNG format. // let _ = img.save(file, image::PNG).unwrap(); image::save_buffer(&Path::new("image.jpg"), &buffer, 980, 612, image::RGB(8)); /* let mut contents = String::new(); if let Err(error) = file.read_to_string(&mut contents) { return Err(IronError::new(error, (status::BadRequest, "The file was not a text"))); } println!("{}", contents);*/ println!(r#"Field "{}" is file "{}":"#, name, filename); } Ok(Response::with((status::Ok, "Multipart data is processed"))) }
标签:
原文地址:http://www.cnblogs.com/mignet/p/5393737.html