School records--java Uploading pictures

Source: Internet
Author: User

Upload Image:

Jsp:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%>

<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix= "FN" uri= "Http://java.sun.com/jsp/jstl/functions"%>


<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<link href= "Css/newstyle.css" rel= "stylesheet" type= "Text/css" >
<script src= "Js/jquery-1.4.2.min.js" type= "Text/javascript" ></script>
<script src= "Js/commfn.js" type= "Text/javascript" charset= "Utf-8" ></script>
<script src= "Js/vli.js" ></script>
<script type= "Text/javascript" >

Function Openupload_ (val) {
var functionId = val;/* Select the current selection */
alert (FUNCTIONID);
Openupload (functionId, ' jpg,gif,jpeg,png ', ' 1 ', callback);
}
function Openupload (functionid,filetype,maxsize,callback) {
var url = "useraction.do?method=gofileupload&";
if (functionid!=null) {
url = url + "functionid=" +functionid+ "&";
}
if (filetype!=null) {
url = url + "filetype=" +filetype+ "&";
}
if (maxsize!=null) {
url = url + "maxsize=" +maxsize;
}
var win = window.showModalDialog (URL, "", "Dialogwidth:300px;dialogheight:150px;scroll:no;status:no");
if (win! = null) {
var Arrwin = Win.split (",");
Callback (arrwin[0],arrwin[1],arrwin[2]);
}
}
/**
* Callback function, get upload file information
* Realname Real file name
* Savename File Save name
* MaxSize file Actual size
*/
function callback (realname,savename,maxsize) {
Alert ("AA");
Other actions after callback
}
</script>
<style type= "Text/css" >
. ll TD {
Border-top: #CaCaCa 1px solid;
Border-left: #CaCaCa 1px solid;
Border-bottom: #CaCaCa 1px solid;
}

.111 TD {
Border-left: #CaCaCa 1px solid;
Border-bottom: #CaCaCa 1px solid;
}
</style>

<body scroll= "No" leftmargin= "0" topmargin= "0" >
<form name= "Projform" id= "Projform" method= "post" action= "/useraction.do?=adddrusersnew" focus= "UserName" enctype = "Multipart/form-data" >
<input type= "hidden" id= "id" name= "id" value= "${user.id}"/>
<input name= "UserName" type= "hidden" value= "${pageform.username}"/>
<input type= "hidden" name= "Pagestyle" value= "Gopage"/> <input
Type= "hidden" name= "Currentpagenum"
Value= "${pageform.currentpagenum}"/> <input type= "hidden"
Name= "Totalpagenum" value= "${pageform.totalpagenum}"/>
<table border= "0" cellspacing= "0" cellpadding= "0" width= "100%" height= "100%" >
<tr>
&LT;TD height= "" bgcolor= "#accff5" >&nbsp;&nbsp; Src= "Images/body/toptitle1.gif" align= "absmiddle" border= "0"/>&nbsp;<strong> Add users </strong>
</td>
</tr>
<tr>
&LT;TD valign= "Top" height= ">"
<!--content Start-up
<table id= "Tdcycle1" width= "100%" border= "0" cellpadding= "0" cellspacing= "0" >
<tr>
&LT;TD height= "bgcolor=" #accff5 "colspan=" 4 ">&nbsp;&nbsp; Src= "Images/body/toptitle1.gif" align= "absmiddle" border= "0"/>&nbsp;<strong> Shipper information </strong>
</td>
</tr>
&LT;TR class= "LL" >
&LT;TD width= "height=" align= "right" > ID:</td>
&LT;TD height= "align=" left "style=" border-right:1px solid #CaCaCa "colspan=" 3 ">
<input type= "hidden" name= "photo" id= "Photo_" ></input>
<input type= "button" onclick= "Openupload_ (this.value)" value= "Upload id"/>
</td>
</tr>
</table>
</table>
<tr>
&LT;TD id= "Splitpage" height= "align=" > "Center"
<a href= "Javascript:submitform (); ></a></td>
</tr>
</table>
</td>

<TD id= splitpage "height=" align= "center" ><a
Href= "Javascript:submitform ();" >Src= "Images/body/confirm.gif" border= "0"/></a></td>
</tr>
</table>
</form>
<!--Ui-dialog--
<div id= "Dialog" ></div>

<div id= "Loading_img"
Style= "Position:absolute; Background: #FFFFFF; Display:none; Z-index:2; width:128; height:128; Border-left:solid #5084B8 1px; Border-top:solid #5084B8 1px; Border-bottom:solid #5084B8 1px; Border-right:solid #5084B8 1px; "
cellspacing= "0" cellpadding= "0" oncontextmenu= "return false" >

</div>

</body>

Jsp:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
pageencoding= "Utf-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >


<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>insert title here</title>

<body>
<form id= "file_upload_id" name= "File_upload_name" action= ". /wlgl/fileupload.do "method=" post "enctype=" Multipart/form-data ">
<input type= "hidden" name= "FunctionId" value= "${functionid}"/>
<input type= "hidden" name= "FileType" value= "${filetype}"/>
<input type= "hidden" name= "maxSize" value= "${maxsize}"/>
<div><input type= "File" Name= "File_upload"/></div>
<c:if test= "${maxsize!=null}" >
<div style= "Font:12" > File max cannot exceed ${maxsize}mb</div>
</c:if>
<c:if test= "${filetype!=null}" >
<div style= "font:12" > file format must be:${filetype}</div>
</c:if>
<div><input type= "Submit" value= "Upload"/></div>
</form>
</body>

Xml

<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>
Com.hysoft.action.FileUploadServlet
</servlet-class>
<init-param>
<!--the size of the upload file memory buffer greater than this value will be written directly to the temporary disk storage directory--
<param-name>threshold</param-name>
<param-value>10485760</param-value><!--1M--
</init-param>
<init-param>
< temporary disk storage directory!--server-side upload files--
<param-name>repository</param-name>
<param-value>/uploadFile/</param-value>
</init-param>
<init-param>
<!--allows the maximum size of a single upload file--
<param-name>fileSizeMax</param-name>
<param-value>8388608</param-value><!--8m=2*1024*1024--
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/fileUpload.do</url-pattern>
</servlet-mapping>

Java:

Package com.hysoft.action;

Import Java.io.File;
Import java.io.IOException;
Import java.util.List;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import Org.apache.commons.fileupload.FileItem;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;
Import Org.apache.log4j.Logger;
Import org.apache.struts.action.ActionErrors;

Import Com.hysoft.utils.UUID;


public class Fileuploadservlet extends HttpServlet {

Private static final long serialversionuid = 8088769669368270752L;

Log records
Logger log = Logger.getlogger (This.getclass (). GetName ());
@Override
protected void doget (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {
DoPost (request, response);
}

@SuppressWarnings ({"Unchecked", "unused"})
@Override
protected void DoPost (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {

Actionerrors errors = new Actionerrors ();

Save user Information
Users u = ubusi.adddrusernew (uform, errors);
Save picture
String temp = request.getsession (). Getservletcontext (). Getrealpath ("/") + "temp"; Temp directory
String path = Request.getsession (). Getservletcontext (). Getrealpath ("/") + "UploadFile"; Upload a file to store directory
temp = Temp.replace ("Wlgltemp", "wlgl/temp");
Path = Path.replace ("Wlgluploadfile", "wlgl/uploadfile");

Gets and resolves file types and supports maximum values
String functionId = Request.getparameter ("FunctionId");
String FileType = Request.getparameter ("FileType");
String maxSize = Request.getparameter ("MaxSize");

Diskfileitemfactory factory = new Diskfileitemfactory ();
Maximum cache
Factory.setsizethreshold (5*1024);
Set Temp file directory
Factory.setrepository (new File (temp));
Servletfileupload upload = new Servletfileupload (factory);
if (maxsize!=null &&! "". Equals (Maxsize.trim ())) {
Maximum file limit
Upload.setsizemax (integer.valueof (maxSize) *1024*1024);
}
try {
Get a list of all files
list<fileitem> items = upload.parserequest (request);
for (Fileitem Item:items) {
if (!item.isformfield ()) {
Filename
String fileName = Item.getname ();
Check file suffix format
String fileend = filename.substring (Filename.lastindexof (".") +1). toLowerCase ();
if (filetype!=null &&! "". Equals (Filetype.trim ())) {
Boolean isrealtype = false;
string[] Arrtype = Filetype.split (",");
for (String Str:arrtype) {
if (Fileend.equals (Str.tolowercase ())) {
Isrealtype = true;
Break
}
}
if (!isrealtype) {
Tip error Message: File format is incorrect
Log.error ("file format is incorrect!");
}
}
Create a file unique name
String uuid = uuid.create ("file");
True upload path
StringBuffer Sbrealpath = new StringBuffer ();
Sbrealpath.append (Path). Append ("/"). Append (UUID). Append ("."). Append (fileend);
Write file
File File = new file (sbrealpath.tostring ());
Item.write (file);
Upload successful, return data to the parent form: Real file name, virtual file name, file size
StringBuffer sb = new StringBuffer ();
Sb.append ("window.returnvalue="). Append (FileName). Append (","). Append (UUID). Append ("."). Append (Fileend). Append (","). Append (File.length ()). Append ("';");
Sb.append ("Window.close ();");
Log.info ("Upload file success, JS information:" +sb.tostring ());
}
}
}catch (Exception e) {
Hint error: such as file size
Log.error ("Upload failed, file size cannot exceed" +maxsize+ "m!", e);
Log.error ("Upload file Exception!", E);
}
}


}

School records--java uploading pictures

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.