I have been busy with some small things over the past few days, and I have nothing to do. Today, let's come and play a simple stuff. It is how to return images under MVC. I believe that in traditional webform, everyone knows how to get the images. This is not limited to one. However, in MVC, which has a strict architecture, friends who are new to contact may not know how to implement it.
First of all, we should start with the Controller. A friend asked me yesterday, isn't the Controller generally a return view? How to return the image? Of course, the Controller class does not return image either. In the previous example, we returned JSON. In fact, we can let it return a file stream. At the beginning, I also thought about using viewdata, however, the view page can only be accessed through the server.CodeIf you want to use JS, it is not easy.
The Controller class has a file method. Of course, it has n reloads and the returned objects are different. here we need to find the file method that returns the filecontentresult type, because I have tested it, in the element, the src attribute cannot read the content of the filestreamresult object, which is blank. Therefore, you cannot return filestreamresult to obtain the result.
Please refer to the following code. It is not complex. I will first draw a rectangle, then draw some text on the rectangle, and then return.
Public actionresult getimg () {bitmap BMP = new Bitmap (100, 35); graphics G = graphics. fromimage (BMP); G. clear (color. white); G. fillrectangle (brushes. red, 2, 2, 65, 31); G. drawstring ("Learning MVC", new font ("", 15f), brushes. yellow, new pointf (5f, 5f); memorystream MS = new memorystream (); BMP. save (MS, system. drawing. imaging. imageformat. JPEG); G. dispose (); BMP. dispose (); Return file (Ms. toarray (), "image/JPEG ");}
Note that this method is defined in your controller and belongs to an action.
On the front-end page, we will handle this.
<Div> </div>
In this way, we can use js to perform operations as needed, such as returning random images or verification codes.