File upload servlet gets message content from Httpservletrequest.getinputstream ()

Source: Internet
Author: User

Recently in the mobile phone upload files, because the phone plug-in using the original stream form of the upload, resulting in the use of spring upload components can not be used, so according to the format of the HTTP protocol, I developed a read file stream upload file method, which found that the mobile phone using Android and Apple when , the head information is not the same, looking for a long time finally using the HTTP protocol upload, empty line as the standard file content and the division of the head, that is, to adapt to different terminal uploads; In addition, upload files, if the character stream, read out the picture files are bad is not open, so are the use of byte stream image file upload. Here is the code (for reference only):

@Note (Note = "Bigant:servlet upload file", author = "Zhangwenbo")
@RequestMapping ({"ModifyPictureByStream2"})
@ResponseBody
Public simplemessage<object> modifyPictureByStream2 (httpservletrequest req, httpservletresponse response) {
This.logger.info ("Modifyheaderpicture have Invoked.filename is");

simplemessage<object> sm = new simplemessage<object> ();

InputStream in = null;

Randomaccessfile accessfile = null;

Bytearrayoutputstream outputstream = null;

FileOutputStream fileout = null;

File tmpfile = null, FileIO = NULL;

try {
Get tags when uploading files
String Boundarytext = Req.getcontenttype (). substring (Req.getcontenttype (). IndexOf ("boundary=") + 9);

cache files in text format first
in = Req.getinputstream ();

Tmpfile = File.createtempfile (Uuid.randomuuid (). toString (), ". txt");

if (tmpfile.exists ()) {
Tmpfile.createnewfile ();
}

Logger.info ("Cache file path is:" + tmpfile.getpath ());

Fileout = new FileOutputStream (tmpfile);

byte[] Tmp_byte = new byte[1024];

int tmp =-1;

while ((TMP = In.read (tmp_byte)) >-1) {
Fileout.write (tmp_byte, 0, TMP);
}

Fileout.flush ();

Fileout.close ();

Analyze data content from file content
Accessfile = new Randomaccessfile (tmpfile, "R");

OutputStream = new Bytearrayoutputstream ();

String line = Accessfile.readline ();

Boolean contentbegin = false;

Boolean hasfilename = false;

String filename = "";

while (true) {
if (!hasfilename) {
int filename_index = Line.indexof ("filename=\" ");

if (Filename_index >-1) {
Contentbegin = true;

filename = line.substring (Filename_index + ten, Line.length ()-1);

SYSTEM.OUT.PRINTLN ("filename is" + filename);

while (! "". Equals (Line.trim ())) {///Here is an empty behavior tag, and if marked with another, the read fails because the header content may not be the same
line = Accessfile.readline ();
}
Hasfilename = true;

Logger.info ("The upload filename is:" + filename);

Continue
}
line = Accessfile.readline ();
}

if (Contentbegin) {
byte[] Temp_byte = new byte[1024];

int byte_len =-1;

while ((Byte_len = Accessfile.read (temp_byte)) >-1) {

String con_temp = new String (temp_byte, 0, Byte_len);

if (Con_temp.indexof (Boundarytext) >-1) {
Break
}
Outputstream.write (temp_byte, 0, Byte_len);
}
Break
}
}

Restore the type of upload file
int filename_index = Filename.indexof (".");

FileIO = File.createtempfile (filename.substring (0, Filename_index), filename.substring (Filename_index));

if (! ( Fileio.exists ())) {
Fileio.createnewfile ();
}

Logger.info ("Target file filepath:" + fileio.getpath ());

Fileout = new FileOutputStream (FileIO);

byte[] Tem_byte = Outputstream.tobytearray ();

System.out.println ("Write file length is:" + tem_byte.length);

Fileout.write (Tem_byte);

Fileout.flush ();

Start uploading files to the target server
map<string, object> postbody = new hashmap<string, object> ();

Postbody.put ("LoginName", Req.getsession () getattribute ("Sessionuserid"));

Bigantbaseres Uploadresult = Bigantclient.getinstance (). Uploadpicture (postbody, filename, FileIO);

This.logger.info ("Upload return msg is" + Uploadresult);

if (null! = Uploadresult) {
if ("1". Equals (Uploadresult.getstatus (). Trim ()))
Sm.set ("Data", Uploadresult.getdata ());
Else
Sm.set ("Message", Uploadresult.getmsg ());
} else {
Sm.set ("message", "Upload fail");
}

} catch (IOException e) {
Logger.info ("Upload the file fail.", e);

Sm.set ("message", "Upload fail");
} finally {
try {
Delete temporary files
if (tmpfile.exists ()) {
Tmpfile.delete ();
}

if (fileio.exists ()) {
Fileio.delete ();
}

if (null! = IN) {
In.close ();
}

if (null! = Fileout) {
Fileout.close ();
}

if (null! = Accessfile) {
Accessfile.close ();
}

if (null! = OutputStream) {
Outputstream.close ();
}
} catch (Exception E2) {
Logger.info ("Release resource fail.", E2);
}
}
return SM;
}


This article is from the "Java" blog, so be sure to keep this source http://zwbjava.blog.51cto.com/2789897/1789880

File upload servlet gets message content from Httpservletrequest.getinputstream ()

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.