Two methods of uploading files with JSP

Source: Internet
Author: User
Tags date format config cos file upload zip
js| uploaded in the use of Java development Enterprise system, especially in connection with the Office-related software development, the file upload is often referred to the requirements of customers. So a good file upload solution can also facilitate the development of this piece.

First of all, the article is for their own record of the development needs after the time, do not rush haha ...

Now in the domestic use of very many generally is two methods to solve the file upload.

Cos.jar + Uploadbean.jar + Filemover.jar
This is very common because of the ease with which we have no need to pay attention to the input and output stream of those files, which frees us from the underlying stream.
Uploadfile,uploadbean,multipartformdatarequest
<%@ page contenttype= "text/html;charset=gb2312"%>
&LT;TITLE&GT;FBYSSS Uploadbean Sample </title>
<!--meta http-equiv= "Content-type" content= "text/html; Charset=iso-8859-1 "-->
<!--meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "-->
<form name= "Form1" method= "POST" action= "sssupload.jsp" enctype= "Multipart/form-data" >
<input name= "title" type= "text" value= "Chinese Characters" >
&LT;TD class= "bodystyle" > Accessories </td>
&LT;TD class= "Bodystyle" > <input name= "Attach" type= "FILE" id= "Attach" size= "M" > </td>
<input name= "OK" type= "submit" value= "submitted" >
</form>
2. Read form page sssgetdata.jsp
<!--
//==========================================================================
File: Uploadbean Upload Instance
Features: Solve Chinese garbled, complete file upload, and provide upload name solution
Author: fbysss
Msn:jameslastchina@hotmail.com
//==========================================================================
-->
<%@ page contenttype= "TEXT/HTML;CHARSET=GBK"%>
<%@ page language= "java" import= "com.jspsmart.upload.*"%>
<%@ page import= "Java.text.SimpleDateFormat"%>
<%@ page import= "Java.io.File"%>
<%@ page import= "java.util.*"%>
<%@ page import= "javazoom.upload.*"%>
<%@ page import= "uploadutilities. FileMover "%>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<%
Request.setcharacterencoding ("GBK"),//Set the encoding format, you do not have to turn the code.
FileMover FileMover = new FileMover ()//You can also use the form of Jsp:usebean in your own instance.
Uploadbean Upbean = new Uploadbean ();
Multipartformdatarequest mrequest = null;
Hashtable files = null;

if (Multipartformdatarequest.ismultipartformdata (Request))
{
Mrequest = new Multipartformdatarequest (Request,null,100*1024*1024,multipartformdatarequest.cosparser, "GBK"); Note that the encoding parameters are also set here
String sTt0 = Mrequest.getparameter ("title");
Out.println ("<br>title0" is: "+stt0+");
String sTt1 = new String (Stt0.getbytes ("iso-8859-1"), "GBK");
Out.println ("<br>title1" is: "+stt1+");
This is used to test whether the title argument is correct. When debugging, add a sentence of if (true) return;
Files = Mrequest.getfiles ();
}


Get the file name before the modification
String soldfilename =mrequest.getparameter ("Oldfilename");
Out.println ("Soldfilename:" +soldfilename);
String Swebrootpath = Request.getrealpath ("/");//Get the root of your Web application.
String spath=swebrootpath+ "Attach";
int ifilecount = 0;
String sserverfilename= "";
String slocalfilename = "";
File acquisition
if ((Files!= null) | | (!files.isempty ())) {

Ifilecount = Files.size ();
UploadFile file = (uploadfile) files.get ("Attach");
Slocalfilename=file.getfilename ();
Out.println ("Slocalfilename:" +slocalfilename);
int ii= slocalfilename.indexof ("."); Suffix of filename
String sExt = slocalfilename.substring (Ii,slocalfilename.length ());
Get a file name that doesn't duplicate
Java.util.Date dt = new Java.util.Date (System.currenttimemillis ());
SimpleDateFormat FMT = new SimpleDateFormat ("Yyyymmddhhmmsssss");
Sserverfilename= fmt.format (DT);
Sserverfilename =sserverfilename + sExt;
If the directory does not exist, create a new
File dir =new file (spath);
if (!dir.exists ()) {
Dir.mkdirs ();
}
Upbean.setfolderstore (spath);/Set the directory to upload
Upbean.adduploadlistener (FileMover)//Increase Filmover Monitor
Filemover.setnewfilename (Sserverfilename)//Set the file name on the server
Upbean.store (Mrequest, "attach");/upload
Out.println ("File path is" +spath+ "/" +sserverfilename);
}

%>

Demo Note: Cos.jar,uploadbean.jar,filemover.jar These packages must have.
Required Download Address:
Uploadbean1.5:http://wcarchive.cdrom.com/pub/simtelnet/winnt/java/uploadbean1_5.zip
Filemover1.3:http://www.javazoom.net/jzservlets/uploadbean/addons/filemover1.3.zip
Reference Download Address:
chinesupload Example: Http://www.javazoom.net/jzservlets/uploadbean/addons/ChineseUpload.zip
Refer to an article in Fbysss
2. Org.apache.struts.upload.FormFile
The Org.apache.struts.upload.FormFile class of the Struts1.1. It's very convenient not to write on your own. Also do not have to write a JSP call Jspsmartupload can be done.


Select Upload File page: selfile.jsp


--------------------------------------------------------------------------------
<%@ taglib uri= "/web-inf/struts-html.tld" prefix= "html"%>

--------------------------------------------------------------------------------
Uploadaction.java
--------------------------------------------------------------------------------
Import java.io.*;
Import javax.servlet.http.*;
Import org.apache.struts.action.*;
Import Org.apache.struts.upload.FormFile;

/**
* <p>Title:UpLoadAction</p>
* <p>description:qrrsmms </p>
* <p>copyright:copyright (c) jiahansoft</p>
* <p>Company:jiahansoft</p>
* @author WANGHW
* @version 1.0
*/

public class Uploadaction extends Action {
Public Actionforward Execute (actionmapping mapping,
Actionform form,
HttpServletRequest request,
HttpServletResponse response)
Throws Exception {
if (Form instanceof Uploadsform) {//if form is Uploadsform
String encoding = request.getcharacterencoding ();
if ((Encoding!= null) && (Encoding.equalsignorecase ("Utf-8"))
{
Response.setcontenttype ("text/html; charset=gb2312 ");//If no encoding is specified, the encoding format is gb2312
}
Uploadform theform = (uploadform) Form;
Formfile file = Theform.getthefile ();//Get uploaded files
try {
InputStream stream = File.getinputstream ()//read the file into
String FilePath = Request.getrealpath ("/");//Take current system path
Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
OutputStream BOS = new FileOutputStream (FilePath + "/" +
File.getfilename ())//create an output stream of uploaded files
System.out.println (filepath+ "/" +file.getfilename ());
int bytesread = 0;
byte[] buffer = new byte[8192];
while ((bytesread = stream.read (buffer, 0, 8192))!=-1) {
Bos.write (buffer, 0, bytesread);//write file to server
}
Bos.close ();
Stream.Close ();
}catch (Exception e) {
System.err.print (e);
}
Request.setattribute ("Dat", file.getfilename ());
Return Mapping.findforward ("display");
}
return null;
}
}


--------------------------------------------------------------------------------

Uploadform.java

--------------------------------------------------------------------------------


Import Javax.servlet.http.HttpServletRequest;
Import org.apache.struts.action.*;
Import org.apache.struts.upload.*;

/**
* <p>Title:UpLoadForm</p>
* <p>description:qrrsmms </p>
* <p>copyright:copyright (c) jiahansoft</p>
* <p>Company:jiahansoft</p>
* @author WANGHW
* @version 1.0
*/

public class Uploadform extends Actionform {
public static final String error_property_max_length_exceeded = "org.apache.struts.webapp.upload.MaxLengthExceeded";
protected Formfile thefile;
Public Formfile Getthefile () {
return thefile;
}
public void Setthefile (Formfile thefile) {
This.thefile = thefile;
}
Public actionerrors Validate (actionmapping mapping, httpservletrequest request)
{
Actionerrors errors = null;
Has the maximum length been exceeded?
Boolean maxlengthexceeded = (Boolean)
Request.getattribute (multipartrequesthandler.attribute_max_length_exceeded);
if ((maxlengthexceeded!= null) && (Maxlengthexceeded.booleanvalue ()))
{
Errors = new Actionerrors ();
Errors.add (error_property_max_length_exceeded, New Actionerror ("maxlengthexceeded"));
}
return errors;

}
}
This is the corresponding form, there are other attributes can be set, you can refer to the example struts upload examples.



--------------------------------------------------------------------------------

Struts-config.xml

--------------------------------------------------------------------------------

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE struts-config Public "-//apache Software foundation//dtd struts Configuration 1.1//en" "http:// Jakarta.apache.org/struts/dtds/struts-config_1_1.dtd ">
<struts-config>
<form-beans>
<form-bean name= "Uploadsform" type= "Uploadform"/>
</form-beans>
<action-mappings>
<action name= "Uploadsform" type= "uploadaction" path= "/uploadsaction" >
<forward name= "Display" path= "/display.jsp"/>
</action>
</action-mappings>
</struts-config>
<!--display.jsp Just write a success page-->



Related Article

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.