Home > front end >  MVC project image to upload
MVC project image to upload

Time:11-29

HTML is selected in the picture button:
Head & lt;/div>


In Jquery FormData binary object splicing and commit:
The script type="text/javascript" & gt;
//avatars change
The function uploadImage (obj) {
Var formData=https://bbs.csdn.net/topics/new formData ();//create FormData object, splicing form form data in the form of key-value pairs (multipart/form - data, pictures and media files)
//in the input file list information
Var files=$(obj). Prop (" files ");
//stitching image file flow information
The console. The log files ([0]);
FormData. Append (" file ", files [0]).
$. Ajax ({
Url: "/FileUpload/FileLoad/,"
Type: "POST",
Data: formData,
Async: false,
DataType: "json",
//tell jQuery don't sent to deal with data
ProcessData: false,
//tell jQuery don't set the content-type request header
ContentType: false,
BeforeSend: function () {
The console. The log (" is ongoing, please wait ");
},
Success: the function (data) {
If (data. IsSuccess) {
The console. The log (data. The path);
The console. The log (" image upload success ");
//dynamic assignment
$(" # headPortrait "). The CSS (" background - image ", "url (" + data. The path +") ");
}
The else {
The console. The log (" network is unusual, please try again later ");
}
},
Error: function (data) {
The console. The log (" error2 ");
}
});
}
</script>

The server receives the Ajax asynchronous binary image files submitted information, and save the
To verify and handle HTML input data in the form the information needed to encapsulate, such as FromData patchwork of file
FemContext to verify and handle HTML form input data encapsulate
[HttpPost]
Public ActionResult FileLoad (FormContext context)
{
HttpPostedFileBase HttpPostedFileBase=Request. Files [0];//get the binary image file flow
If (httpPostedFileBase!=null)
{
Try
{
ControllerContext. HttpContext. Request. ContentEncoding=Encoding. GetEncoding (" utf-8 ");
ControllerContext. HttpContext. Response. Charset="utf-8";

String fileName=Path. GetFileName (httpPostedFileBase. FileName);//the original file name
String fileExtension=Path. GetExtension (fileName);//file extension

Byte [] fileData=https://bbs.csdn.net/topics/ReadFileBytes (httpPostedFileBase);//file conversion into a binary bytes

The string result=SaveFile (fileExtension fileData);//file
If (string. IsNullOrEmpty (result))
{
Return a Json (new {isSuccess=false, path="", errorMsg=" failed to upload file "});
}

Return Json (new {isSuccess=true, path=result});
}
The catch (Exception e)
{
Return a Json (new {isSuccess=false, path=""});
}
}
The else
{
Return a Json (new {isSuccess=false, path=""});
}
}


///& lt; Summary>
///to circulate the file into the binary bytes
///& lt;/summary>
///& lt; Param name="fileData & gt;" Image file flow & lt;/param>
///& lt; Returns>
Private byte [] ReadFileBytes (HttpPostedFileBase fileData)
{
Byte [] data;
Using (Stream inputStream=fileData. InputStream)
{
MemoryStream MemoryStream=inputStream as MemoryStream;
If (memoryStream==null)
{
MemoryStream=new memoryStream ();
InputStream. CopyTo (memoryStream);
}
Data=(https://bbs.csdn.net/topics/memoryStream.ToArray);
}
return data;
}

///& lt; Summary>
///save the file
///& lt;/summary>
///& lt; Param name="fileExtension & gt;" File extension & lt;/param>
///& lt; Param name="fileData & gt;" Image binary information & lt;/param>
///& lt; Returns>
Private string SaveFile (string fileExtension, byte [] fileData)
{
The string result;
Try
{

String saveName=Guid. NewGuid (). The ToString () + fileExtension;//save the file name

//file upload after save the path
String basePath="UploadFile";
String the -savedir=DateTime. Now. ToString (" yyyy - MM - dd ");
String savePath=System.IO.Path.Com bine (the -savedir saveName);

String serverDir=System.IO.Path.Com bine (Server. MapPath (" ~/"), basePath, the -savedir);
if (! System. IO. Directory. The Exists (serverDir))
{
System. IO. Directory. CreateDirectory (serverDir);
}
String fileNme=System.IO.Path.Com bine (serverDir saveName);//save the full path to the file
System. IO. File. WriteAllBytes (fileNme fileData);//WriteAllBytes to create a new file, according to the corresponding file stream, if existing cover
//return the complete picture save address
Result="/" + basePath + "/" + "/" + + the -savedir saveName;
}
The catch (Exception)
{
Result="errors";
}
return result;
}
}

CodePudding user response:

The building Lord want to express what is this

CodePudding user response:

if (! System. IO. Directory. The Exists (serverDir))
{
System. IO. Directory. CreateDirectory (serverDir);
}
This is a bit redundant, CreateDirectory if is an existing directory, will be ignored, and not an error, so you can direct CreateDirectory

CodePudding user response:

  • Related