Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ServletInputStream () input stream to read pictures

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use the ServletInputStream () input stream to read pictures", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to use the ServletInputStream () input stream to read pictures"!

Catalogue

Problem description

Project structure

Cause of the problem

Solution method

Summary and review

Problem description

Recently, I encountered the need to upload pictures to the server. I learned how to save pictures to a specified directory using form in native servlet.

Idea: front-end submission-servlet to get inputstream- output to local

After getting the input stream, the output to the local can not open the prompt for damage / 0kb. From the Internet, I saw that there were two packages, io and fileupload, which said they needed apache. What I want is to deal with it without the help of a third-party toolkit (tomcat is also a third-party, hehe, pure should be the use of socket)

Project structure

As shown in the figure: instead of using the rest of the components, create a dynamic java project

Cause of the problem

An article was found on the Internet, which probably means that uploading a file is not a simple file stream, it is different from the local io and there are some things in it. It cannot be parsed according to the way of local upload and download. Including some delimiters\ and some information about the form, which needs to be reprocessed.

Solution method

Parse the stream of the picture manually, remove the excess from it, and then output the resulting pure file stream to the specified location

Summary and review

This question can not find the current time of the post, usually 2-3 years ago let me a little surprised. Knowing it but not knowing why, sooner or later, it will be held back by others. In a dazzling array of frameworks, copying does solve the problem and really gets twice the result with half the effort.

If you write code, you should check more and read more api documents.

Hit the code more, or you don't know why, and you've been doing this all weekend with such a little problem.

Package server;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.io.StringReader;import java.util.HashMap;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet Import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@SuppressWarnings ("serial") @ WebServlet (name = "streams", urlPatterns = "/ UploadServlet.do") public class CsvTest extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ("text/html" Charset=UTF-8 "); PrintWriter out = response.getWriter (); final int NONE = 0; / / status code, indicating that there is no special operation final int DATAHEADER = 1; / / indicates that the header information to be read on the next line is final int FILEDATA = 2; / / indicates that the uploaded file and binary data are to be read next final int FIELDDATA = 3 / / indicates the following text value to read to the form field / / the total length of the request message entity (the data length except the header in the request message) int totalbytes = request.getContentLength (); File f; / uploaded file is stored on the server / / Byte array containing the request message entity byte [] dataOrigin = new byte [totalbytes] / / for post forms with multiple files, b provides the operation to extract file data as a copy of the original data byte [] b = new byte [totalbytes]; / / request message type String contentType = request.getContentType (); String fieldname = ""; / / name of the form field String fieldvalue = "" / / the value of the form field String fileFormName = ""; / / the name of the uploaded file in the form String fileRealName = ""; / / the real name of the uploaded file String boundary = ""; / / the delimiter string String lastboundary = ""; / / the delimiter string int fileSize = 0 / / File length / / Hash table Map formfieldsTable = new HashMap () containing the name / value of the form field; / / Hash table Map filenameTable = new HashMap () containing the name / file name of the file field; / / find the definition of the delimiter int pos = contentType.indexOf ("boundary=") in the header type; int pos2 / / position2 if (pos! =-1) {pos + = "boundary=" .length (); boundary= "-" + contentType.substring (pos); / / parse the delimiter lastboundary = boundary + "-"; / / get the ending delimiter} int state = NONE / / the data input stream whose starting state is NONE / / gets the request message DataInputStream in = new DataInputStream (request.getInputStream ()); in.readFully (dataOrigin); / / reads the contents of the message entity into the byte array dataOrigin () according to the length; / / closes the data flow String reqcontent = new String (dataOrigin) / / get the string representing the entity from the byte array / / get the output buffer stream BufferedReader reqbuf = new BufferedReader (new StringReader (reqcontent)) from the string; / / set the loop flag boolean flag = true; / / int I = 0; while (flag = = true) {String s = reqbuf.readLine () If (s = = lastboundary | | s = = null) break; switch (state) {case NONE: if (s.startsWith (boundary)) {/ / if the delimiter is read, it indicates the header information of the next line state = DATAHEADER; / / I + = 1;} break; case DATAHEADER: pos = s.indexOf ("filename=") / / first determine whether this is the header information of a text form field or the header information of an uploaded file if (pos =-1) {/ / if it is the header information of a text form field, resolve the name of the form field pos = s.indexOf ("name="); pos + = "name=" .length () + 1 / / 1 indicates that the placeholder s = s.substring (pos); int l = s.length (); s = s.substring (0, l-1); / / should be "fieldname= s; / / the name of the form field should be put in fieldname out.print (" fieldname= "+ fieldname); state = FIELDDATA / / set the status code and prepare to read the value of the form field} else {/ / if it is the header of the file data, store this line first, which is used to locate String temp = s in the byte array; / / first parse the file name pos = s.indexOf ("name="); pos + = "name=" .length () + 1 / / 1 means placeholder pos2 = s.indexOf ("filename="); String S1 = s.substring (pos, pos2-3); / / 3 means "; add a space fileFormName = S1; pos2 + =" filename= ".length + 1; / / 1 means placeholder s = s.substring (pos2); int l = s.length () S = s.substring (0, l-1); pos2 = s.lastIndexOf ("\\"); / / Settings for IE browsers s = s.substring (pos2 + 1); fileRealName= s; out.print ("fileRealName=" + fileRealName + "

"); out.print (" fileRealName.length () = "+ fileRealName.length () +"

"); if (fileRealName.length ()! = 0) {/ / make sure that a file has been uploaded / / the following section fetches the file's data from the byte array b = dataOrigin; / / copies the original data to extract the file pos = byteIndexOf (b, temp, 0) / / locate the line / / locate the next line, 2 indicates that a carriage return and a line feed occupy two bytes b = subBytes (b, pos + temp.getBytes (). Length + 2, b.length); / / read another line of information, which is the Content-type s = reqbuf.readLine () of this part of the data / / set the file input stream and prepare to write the file f = new File ("C:" + File.separator + "Users" + File.separator + "Administrator" + File.separator + "Desktop" + File.separator + fileRealName); DataOutputStream fileout = new DataOutputStream (new FileOutputStream (f)) / / the next line of the byte array, 4 means that two carriage returns and line feeds occupy 4 bytes, the carriage return line of this line is 2 bytes, and the next line of Content-type is a blank line represented by carriage return line feeds, which occupies 2 bytes / / the starting position b = subBytes (b, s.getBytes (). Length + 4, b.length) of the file data. Pos = byteIndexOf (b, boundary, 0); / / locate the end of the file data b = subBytes (b, 0, pos-1); / / get the file data fileout.write (b, 0, b.length-1); / / save the file data to fileout.close (); fileSize = b.length-1 / / the file length is stored in fileSize out.print ("fileFormName=" + fileFormName + "filename=" + fileRealName + "fileSize=" + fileSize + "

"); filenameTable.put (fileFormName, fileRealName); state = FILEDATA;}} break; case FIELDDATA: / / read the value of the form field s = reqbuf.readLine (); fieldvalue= s; / / save to fieldvalue out.print (" fieldvalue= "+ fieldvalue +"

"); formfieldsTable.put (fieldname, fieldvalue); state = NONE; break; case FILEDATA: / / if the file data is not analyzed, read while ((! s.startsWith (boundary)) & & (! s.startsWith (lastboundary) {s = reqbuf.readLine (); if (s.startsWith (boundary)) {state = DATAHEADER } else {break;}} break;}} / / specifies the content type, and can display Chinese out.println ("

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report