Image upload and echo back end chapter

Source: Internet
Author: User
Tags save file

Image upload and echo back end chapter

Let's look at the effect first.

After an image upload and echo, we come to the actual situation of the entire process of uploading, today we will get through the front and back, we come to the real understanding, we upload the file, to what kind of form to the server, is also a picture? Wait, we'll find out.

Before we start the actual battle, let's do some preparatory work, such as creating a new Java Web project, if you don't understand this, I suggest you learn javaweb, and go to my public number for a tutorial on this. We named our project Upimg, we set up a Web package and a util package for him, and then we copy the code from the previous front-end image back to the project, and we look at the project

Let's take a look at the project.

In this case, our basic framework is done, we first use form form to live a piece of the upload, the next issue we will be AJAX to achieve asynchronous image upload, we first add material to our front-end code

<form action="upload" method="post" enctype="multipart/form-data">    <div class="uploadImgBtn" id="uploadImgBtn">        <input class="uploadImg" type="file" name="file" multiple id="file">    </div>    <input type="submit" value="上传"></form>

This style I will no longer beautify, we look at the effect

In this case, our front-end is basically finished, let me explain some of the code, the Enctype properties of the form:

1, Default properties: Application/x-www-form-urlencoded, only the Value property values in the form field are processed, and forms with this encoding process the value of the form field into URL encoding

2. Multipart/form-data, this encoding form will process the form data in a binary-stream way. This encoding will also encapsulate the contents of the file domain specified in the request parameters.

3, Text/plain, this method is mainly used to send mail directly through the form

Next we explain the idea of file upload,
1. First form submission
2. Binary encoding of data and attachments
3. Use binary stream to get content in servlet

We already know the idea, so let's start coding.
Let's start with a new class under the Util package, I'll name it upimgutils, and then we'll code it.

Package Util;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.inputstream;import javax.servlet.http.httpservletrequest;/*** upload Img utils** @author admin**/public class upimgutils {/* * idea 1, get stream information from Request * 2, create a new temporary file, use the output stream to point to this file * 3, close the stream */public static void KeepFile ( HttpServletRequest request) throws IOException {//1, Get stream information from request InputStream Filesource = Request.getin        Putstream (); /* * The storage path for temporary files (we create a new temp folder under WebContent, it's probably because temp is empty, * No folder is created in Tomcat, then you add one in the published project) *        /String TempFileName = Request.getservletcontext (). Getrealpath ("/") + "temp/tempfile.txt";        2, create a temporary file, with the output stream point to this file//build a file Tempfile = new files (tempfilename);        Use the output stream to point to this file FileOutputStream outputstream = new FileOutputStream (tempfile);        We read 10K each time, our files are small, this is enough byte[] B = new BYTE[1024*10];       int n = 0; Read-write file, 1 is marked as empty while ((n = filesource.read (b))! =-1) {outputstream.write (b, 0, N);        }//3, Close flow filesource.close ();    Outputstream.close (); }}

This class is used to read the stream of bytes from the form form, write to a temporary file, and we'll just call our tool to see the effect in a servlet.

package web;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import util.UpImgUtils;public class upload extends HttpServlet {    private static final long serialVersionUID = 1L;    public upload() {        super();        // TODO Auto-generated constructor stub    }    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        UpImgUtils.keepFile(request);    }    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        doGet(request, response);    }}

The code has been written, my project is the Java Web Project 2.5 version, will automatically configure the servlet, configuration, then no longer explain. Let's run a look at the effect

We have seen, in fact, file upload is the binary stream of files uploaded to the server, this is the end of it?

That's certainly not possible ah, we uploaded a picture, then we must hope or picture Ah, we will re-encapsulate a tool class, before encapsulation, we first look at the format of the temporary file

This is what I'm looking for. Two files, the temporary files generated after uploading, we do not combat the actual package of two files, we will combat the actual package a temporary file, so we first put the input tag in the multiple attribute is removed, our front-end automatically generated input tag code is also commented out first, Let's look at the changed code first.

<script> $ (document). Ready (function () {//For the outer box to bind a click event $ ("#uploadImgBtn"). Click (function () { /* 1, first get Input label 2, the input tag binding Change Event 3, the picture echo *///1, go back to the input label            Sign var $input = $ ("#file"); Console.log ($input)//2, bind the Change event $input to the input tag. On ("Change", function () {CONSOLE.L  OG (this)//Supplemental NOTE: Because we set the multiple property to the input tag, you can upload multiple files at once//get the number of selected images var files =                This.files;                var length = Files.length;                Console.log ("Selected" +length+ "Picture"); 3, Echo $.each (Files,function (key,value) {//each time will only traverse a picture data var div = do                    Cument.createelement ("div"), img = document.createelement ("img");                    Div.classname = "pic";                    var fr = new FileReader ();    Fr.onload = function () {                    Img.src=this.result;                        Div.appendchild (IMG);                    Document.body.appendChild (DIV);                } fr.readasdataurl (value);             })//////////////////4, we remove//the id attribute of the current input tag to $input. REMOVEATTR ("id");// We make a mark, and then add another class name in class called test//var newinput = ' <input class= "uploadimg test" type= "file" Name= "        File "multiple id=" file ">";//$ (this). Append ($ (newinput)); }) </script>

When we look at a file, the format of the temp file

Let us analyze, the second row of filename is what we need, this is the name of the file, we have seen the Chinese name garbled, one will encode the time we need to solve; the 4th line has a blank line, to the 5th line of time only to our body part; We have a space at the end of our body. Now that we know this, we'll go and refine our tool class.

Package Util;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.inputstream;import java.io.randomaccessfile;import javax.servlet.http.httpservletrequest;/*** Upload Img    utils** @author Admin**/public class Upimgutils {/* * idea 1, get stream information from Request * 2, create a new temporary file, point to this file with the output stream * 3, close the stream */public static void KeepFile (HttpServletRequest request) throws IOException {//1, Get stream information from request Inputstre    Am Filesource = Request.getinputstream (); /* * The storage path for temporary files (we create a new temp folder under WebContent, it's probably because temp is empty, * No folder is created in Tomcat, and then you add one in the published project) */String    TempFileName = Request.getservletcontext (). Getrealpath ("/") + "temp/tempfile.txt";    2, create a temporary file, with the output stream point to this file//build a file Tempfile = new files (tempfilename);    Use the output stream to point to this file FileOutputStream outputstream = new FileOutputStream (tempfile);    We read 10K each time, our files are small, this is enough byte[] B = new BYTE[1024*10];    int n = 0; Read-write file, 1 identifies as empty while ((n = Filesource.reaD (b))! =-1) {outputstream.write (b, 0, N);    }//3, Close flow filesource.close ();    Outputstream.close (); The second part ... ..... ..... ..... ..... ....... ....................../** * Ideas * 1, get the name of the file, and solve the Chinese garbled * 2, get the contents of the file * 3, Bao    Save file *////Second Part 1, get the name of the file, and solve the Chinese garbled randomaccessfile randomfile = new Randomaccessfile (tempfile, "R"); Randomfile.readline ();//read a row of String str = Randomfile.readline ();//Read the second line int beginindex = Str.lastindexof ("Filename= \ "") + 10;//location to the beginning of the file name int endIndex = Str.lastindexof ("\" ");//Locate to the end of the file name String filename = str.substring (begininde    x, EndIndex);    Determine if the file name is the full path name or just the file name (Google and Firefox are just filenames, Microsoft Series is the full path name) EndIndex = filename.lastindexof ("\ \") + 1;    if (EndIndex >-1) {filename = filename.substring (endIndex);  }//After the above steps, we have obtained the filename, we also need to solve the problem of Chinese name garbled//resolution of the upload file Chinese name garbled filename = new String (filename.getbytes ("iso-8859-1"),    "UTF-8");    SYSTEM.OUT.PRINTLN ("FileName:" + filename); Part 2, get the contents of the file//reposition the file pointerTo the file header Randomfile.seek (0);    Long startposition = The position of the 0l;//body begins with int i = 1; while ((n = randomfile.readbyte ())! =-1 && i <=4) {if (n = = ' \ n ') {startposition = Rand            Omfile.getfilepointer ();        i++;    }}//startposition = Randomfile.getfilepointer ()-1;    Get the file contents, end position Randomfile.seek (Randomfile.length ());//pointer positioned to tail long endposition = Randomfile.getfilepointer ();    int j = 1;        while (endposition >= 0 && J <=2) {endposition--;        Randomfile.seek (endposition);        if (randomfile.readbyte () = = ' \ n ') {j + +;    }} endposition = EndPosition-1;    Part 3, save file//settings Save the path of the uploaded file, we good save to temp String Realpath = Request.getservletcontext (). Getrealpath ("/") + "temp";    File FileUpload = new file (Realpath);    File SaveFile = new file (realpath,filename);    Randomaccessfile randomaccessfile = new Randomaccessfile (saveFile, "RW"); Read the contents of a file from a temporary file (based on location) rAndomfile.seek (startposition);        while (StartPosition < endposition) {Randomaccessfile.write (Randomfile.readbyte ());    StartPosition = Randomfile.getfilepointer ();    }////close the input/output stream, delete temporary files randomaccessfile.close ();    Randomfile.close ();    Tempfile.delete (); }}

Let's take a look at the effect

In this case, our upload image has been uploaded successfully, we will upload the image of the URL back to the front-end bar, the code will no longer show, realize it yourself.

How to upload multiple images with the input tag and echo
Image upload and Echo Ajax asynchronous chapter

Image upload and echo back end chapter

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.