Java method for uploading file images to the server.

Source: Internet
Author: User

Java method for uploading file images to the server.

Here I will record a simple and convenient JAVA Upload File image to the server and save it. The specific content is as follows:

The first is page html. Here is a file submission and type.

<Div style = "border: 1px solid red;"> I am adding a temporary image to get media_id to save the database! <Form action = "xxxxxxxxm" enctype = "multipart/form-data" method = "post"> <div style = "display: none; "> <input type =" text "value =" IMAGE "name =" type "/> </div> upload an IMAGE: <input type = "file" name = "file" onchange = "previewImage (this, 'prvid ') "multiple =" multiple "> <br/> <input type =" submit "value =" submit "/> </form> <div id =" prvid "> preview container </div> </div>

Preview image js

Function previewImage (file, prvid) {/* file: file control * prvid: Image preview container */var tip = "Keep CT jpg or png or gif! "; // Set the prompt message var filters = {" jpeg ":"/9j/4 "," gif ":" R0lGOD "," png ": "iVBORw"} var prvbox = document. getElementById (prvid); prvbox. innerHTML = ""; if (window. fileReader) {// html5 solution for (var I = 0, f; f = file. files [I]; I ++) {var fr = new FileReader (); fr. onload = function (e) {var src = e.tar get. result; if (! ValidateImg (src) {alert (tip)} else {showPrvImg (src) ;}} fr. readAsDataURL (f) ;}} else {// downgrade processing if (! /\. Jpg $ | \. png $ | \. gif $/I. test (file. value) {alert (tip);} else {showPrvImg (file. value) ;}} function validateImg (data) {var pos = data. indexOf (",") + 1; for (var e in filters) {if (data. indexOf (filters [e]) === pos) {return e ;}return null;} function showPrvImg (src) {var img = document. createElement ("img"); img. src = src; prvbox. appendChild (img );}}

Then the background will get

@ RequestMapping (params = "method = addCircle") public String addCircle (HttpServletResponse response, HttpServletRequest request) throws IOException {request. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8"); String path = request. getSession (). getServletContext (). getRealPath ("/BackstageShoppingWebsite/images/addCircleimage"); // Save the server address Map <String, String> map = Upload. upload (request, 1024*1024*10, path); String file = map. get ("file"); // name String image = map. get ("type"); // image String newFile = map. get ("newFile"); // return null ;}

Now the focus is to look at the Upload class. This class is basically encapsulated. You can take a look at what needs to be added and modify it. Then, this class uses the cos. jar package.

Package com. web. weixin. bean; import java. io. file; import java. io. IOException; import java. util. date; import java. util. hashMap; import java. util. map; import javax. servlet. http. httpServletRequest; import com. oreilly. servlet. multipart. filePart; import com. oreilly. servlet. multipart. multipartParser; import com. oreilly. servlet. multipart. paramPart; import com. oreilly. servlet. multipart. part; public class U Pload {public static Map <String, String> upload (HttpServletRequest request, int maxSize, String path) {// Save the data key in the form of map. The key is saved to get the name value on the interface. The value Map corresponds to the name on the interface. <String, string> map = new HashMap <String, String> (); Part part = null; try {MultipartParser mrequest = new MultipartParser (request, maxSize); mrequest. setEncoding ("UTF-8"); // traverses all part groups while (part = mrequest. readNextPart ())! = Null) {if (part. isFile () {// determine whether it is a file FilePart filepart = (FilePart) part; // convert it to a file group String fileName = filepart. getFileName (); // get the file name if (fileName! = Null & fileName. length ()> 0) {// get the extension String fileExtName = fileName. substring (fileName. lastIndexOf (". ") + 1 ). toLowerCase (); // upload only images // determine whether the Image Upload format complies with the suffix name. if (fileExtName. equalsIgnoreCase ("jpeg") | fileExtName. equalsIgnoreCase ("png") | fileExtName. equalsIgnoreCase ("jpg") | fileExtName. equalsIgnoreCase ("gif") | fileExtName. equalsIgnoreCase ("ico") | fileExtName. equalsIgnoreCase ("bmp") | fileExtName. equalsIgnoreCase ("flv") | fileExtName. equalsIgnoreCase ("mp4") | fileExtName. equalsIgnoreCase ("mp3") {/* String newFileName = new Date (). getTime () + ". "+ fileExtName; // rename the file name + extension */String newFileName = new Date (). getTime () + fileName; // do not change the image name String newPath = path + "/" + newFileName; // File newFile = new File (newPath ); filepart. writeTo (newFile); // write the file to the corresponding folder. // filepart. getName () gets the name map of the parameter to be received by the request. put (filepart. getName (), newFileName); // save the file information to map. put ("newFile", newFile. toString ();} else {map. put ("geshi", "geshi"); continue;} // indicates that the uploaded image is not} else {map. put ("yes", "yes"); continue; // The image is not uploaded} else if (part. isParam () {// determines whether the parameter ParamPart paramPart = (ParamPart) part; map. put (paramPart. getName (), paramPart. getStringValue () ;}} catch (IOException e) {e. printStackTrace ();} return map ;}}

Cos. jar package download, click the open link

This article has been compiled into Java upload operation tips summary. You are welcome to learn and read this article.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.