Server-side receive upload file operation in servlet

Source: Internet
Author: User

Recently the boss divided a task, the client uses C # to implement the file upload, require me to implement the server-side file receive saved to local and receive a successful return to the client an identity. Read on the Internet, most of the client's file upload operations, very few write service-side processing, take this opportunity to share their own service-side implementation of the processing logic. Nonsense not much to say directly on the code

 Public classReciveservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L PublicReciveservlet () {Super(); //TODO auto-generated Constructor stub    }protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stubdoget (request, response); }    protected voiddoget (httpservletrequest request, httpservletresponse response)throwsServletexception, IOException {

protected void DoPost (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {
TODO auto-generated Method Stub
Doget (request, response);
}

protected void doget (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {
Get uploaded files to save the directory, the uploaded files in the Web-inf directory, do not allow direct access to the outside world, to ensure the security of uploading files
String Savepath = This.getservletcontext (). Getrealpath ("/web-inf/upload");
PrintWriter out = Response.getwriter ();
File File = new file (Savepath);
Determine if the saved directory for the uploaded file exists
if (!file.exists () &&!file.isdirectory ()) {
System.out.println (Savepath + "directory does not exist, need to create");
Create a Directory
File.mkdir ();
}
return value hint
String message = "";
Create a diskfileitemfactory factory
Diskfileitemfactory factory = new Diskfileitemfactory ();
try {
Create a File Upload parser
Servletfileupload upload = new Servletfileupload (factory);
Determine if the data submitted is the data that was uploaded to the form
if (! Servletfileupload.ismultipartcontent (Request)){
Get data in the traditional way
Return
}
System.out.println ("IsM =" +servletfileupload.ismultipartcontent (request));
Using the Servletfileupload parser to parse the uploaded data, the parsing results return a list<fileitem> collection, each fileitem corresponding to the input of a form form
list<fileitem> list = upload.parserequest (request);
for (Fileitem item:list) {
If the data in the Fileitem is encapsulated in an ordinary entry
if (Item.isformfield ()) {
String name = Item.getfieldname ();
transcoding
String value = item.getstring ("UTF-8");
Value = new String (value.getbytes ("iso-8859-1"), "UTF-8");
SYSTEM.OUT.PRINTLN (name + "=" + value);
} else {
If the upload file is encapsulated in Fileitem
Get file name
String filename = Item.getname ();
System.out.println ("filename=" + filename);
if (filename = = NULL | | Filename.trim (). Equals ("")) {
Continue
}
Handles the path portion of the file name of the uploaded files that are obtained, leaving only the file name section
filename = filename.substring (filename.lastindexof ("\ \") + 1);
Gets the input stream of the uploaded file in item
InputStream in = Item.getinputstream ();
Creating buffers
byte buffer[] = new byte[1024];
Creates an output stream object that reads the data from the buffer to the save path
FileOutputStream output = new FileOutputStream (savepath+ "\ \" + filename);
Determine if the data in the input stream has been read out
int len = 0;
The loop reads the input stream into the buffer, (len=in.read (buffer)) >0 indicates that there is data in the input stream
while (len = in.read (buffer)) > 0) {
Writes the data of the buffer to the specified directory (savepath + "\ \" + filename) using the FileOutputStream output stream
Output.write (buffer, 0, Len);
}
In.close ();
Output.close ();
Message = "Success";
}
}
} catch (Fileuploadexception e) {
message = "Failure";
E.printstacktrace ();
}
Out.print (message);

}

Note: In the code, the first red place, here if you send the request to determine whether the form is set enctype= "Multipart/form-data" This item, if not set, FileUpload components can not save the uploaded files.

Since this task client was written in C #, it did not use the form form to submit an HTTP request, so when the colleague's client visited me, Debug was unable to get to the HTTP request when the output of the second red Spot was reached. Later through the online information to find a C # and Java background docking an article holding a try attitude to operate, found incredibly successful, successfully received the C # Client sent. The AVI format video file is saved to the local disk, and the identity of the success is returned. Below is your own online search for C # and Java backend docking address:

http://blog.csdn.net/gavin_dyson/article/details/50526940

Server-side receive upload file operation in servlet

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.