The page elements:
//file selection box
//upload button
Front desk: (1) set the preview picture
//picture (img tag) double-click events
$(" # userPicture "). The dblclick (function () {
//the trigger file input box click event
$(" # File "). Click ();
)};
//file reader
Var fileReader=new fileReader ();
//file input box change events
$(" # File). Change (function () {
//get input box inside the file
Var files=$(" # File). The get (0). Files;
//check file format
If (/^ (? : image \/jpeg | image \/JPG | image \/PNG | image \/| GIF image \/BMP) $/test (the file. Type)) {
//use a file reader read the file
FileReader. ReadAsDataURL (file);
} else {
Alert (" your choice is not a valid image file ");
}
)};
//file reader load events, read after the completion of the trigger
FileReader. onl oad=function (e) {
//set the preview picture, that is, set the img tags the SRC attribute of the
$(" # userPicture "). Prop (" SRC ", e. arget, result);
};
(2) access to files in the input box
//get input box inside the file
Var files=$(" # File "). The get (0) files.
//determine whether the user select the file
If (files. Length & gt; 0 {
//build FormData object
Var formData=https://bbs.csdn.net/topics/new formData ();
//add data to the FromData object
FormData. Append (" file ", the file).
} else {
Alert (" please select to upload pictures!" );
}
(3) sends a request to upload pictures, set the callback
$(" # uploadBtn "). Click (function () {
$. Ajax ({
Method: "POST",
Url:/Main/UploadFile,
Data: formData,
ContentType: false,
ProcessData: false,
Success: the function () {
//set the callback according to actual situation...
}
)};
)};
Background:
Public ActionResult UploadFile (HttpPostedFileBase file) {
//determine whether users to upload pictures
If (the file!=null & amp; & File. ContentLength> 0 {
//determine whether stored images directory exists, directory path determined according to the actual situation, the following for instance
if(! System. IO. Directory. The Exists (for Server MapPath (" ~/Document/picture "))) {
//create a directory
System. IO. Directory. CreateDirectory (Server. MapPath (" ~/Document/picture "));
}
//get file extension
String extension=System. IO. Path. GetExtension (file. The fileName);
//stitching filename, determined according to the actual situation, the following for instance
The string fileName=DateTime. Now. ToString (" yyyyMMddHHmmss ") + the extension;
//stitching file path
String filePath=Server. MapPath (" ~/Document/picture/") + fileName;
//save the file to disk
File. The SaveAS (filePath);
//filename to save to the database
According to the actual situation to save file name to the corresponding database table
} else {
Return a json (" please select to upload pictures!" , JsonRequestBehavior. AllowGet);
}
}
CodePudding user response: