Image upload and display of mobile development

Source: Internet
Author: User
Tags save file temporary file storage

1. Uploading, using Servlets and Ajax

(1) The package to be introduced:

(2) Configuring Web. Xml

(3) Procedures for introducing Servlets

Servlet Code:

Package upload;

Import java.sql.*;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.Date;
Import java.util.List;

Import Javax.servlet.ServletConfig;
Import Javax.servlet.ServletContext;
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.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
*
* File Upload specific steps: 1) Get Disk File entry Factory Diskfileitemfactory to guide package 2) Use request to get the real path
*, for temporary file storage, and final file storage, the two storage locations can be different, or the same 3) set some properties on the Diskfileitemfactory object
* 4) High-level API file upload processing servletfileupload upload = new Servletfileupload (factory);
* The purpose is to call the Parserequest (request) method to get the Fileitem collection list,
*
* 5) in the Fileitem object to obtain information, traverse, to determine whether the information submitted by the form is ordinary text information to do another 6) the first kind. Provided by a third party
* Item.write (New File (Path,filename)); Write directly to the second type on disk. Manual processing
*
*/

Public class Uploadprocessorservlet extends HttpServlet {
private static final long serialversionuid = 1L;
The directory where the file is saved
private static String Path_folder = "/";
directory where temporary files are stored
private static String Temp_folder = "/";


@Override
public void init (ServletConfig config) throws servletexception {
ServletContext servletctx = Config.getservletcontext ();
//Initialize path
//Save file directory
Path_folder = Servletctx.getrealpath ("/upload");
The directory where the temporary files are stored, the directory where the xxx.tmp files are stored
Temp_folder = Servletctx.getrealpath ("/uploadtemp");
}

/**
* @see httpservlet#doget (httpservletrequest request, HttpServletResponse
* response)
*/
Public void Doget (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {
Request.setcharacterencoding ("Utf-8"); Set the encoding
response.setcharacterencoding ("Utf-8");
Response.setcontenttype ("Text/html;charset=utf-8");
//Get Disk File entry Factory
Diskfileitemfactory factory = new Diskfileitemfactory ();

//If you do not have the following two lines set up, upload large files will occupy a lot of memory,
//Set up a temporary storage room, this storage room can be different from the final directory to store files
/**
* Principle it is to save to the temporary storage room, and then in the actual write to the corresponding directory of the hard On the disk, when uploading a file, actually uploaded two copies, the first one is in. TEM
* Format and then write it to the corresponding directory hard disk
*/
Factory.setrepository (new file (temp_folder ));
//Sets the size of the cache, which is placed directly into the temporary storage room
Factory.setsizethreshold (1024x768) when the capacity of the uploaded file exceeds the cache;

High level of API File upload processing
Servletfileupload upload = new Servletfileupload (factory);

try {
The information submitted is in this list.
This means that multiple files can be uploaded
Please organize your own code
list<fileitem> list = upload.parserequest (request);
Get the uploaded file
Fileitem item = getuploadfileitem (list);
Get file name
String filename = getuploadfilename (item);
The file name after saving
String savename = new Date (). GetTime () + filename.substring (Filename.lastindexof ("."));
Browser access path to the picture after saving
String Picurl = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () + Request.getcontextpath () + "/upload/" +savename;

SYSTEM.OUT.PRINTLN ("Storage directory:" + Path_folder);
SYSTEM.OUT.PRINTLN ("FileName:" + filename);
SYSTEM.OUT.PRINTLN ("Browser access path:" + Picurl);

Actually write to disk
Item.write (New File (Path_folder, savename)); Provided by third parties

PrintWriter writer = Response.getwriter ();

Writer.print ("{");
Writer.print ("msg:\" File Size: "+item.getsize () +", File name: "+filename+" \ "");
Writer.print (", picurl:\" "+ Picurl +" \ "");
Writer.print ("}");

Writer.close ();

} catch (Fileuploadexception e) {
E.printstacktrace ();
} catch (Exception e) {
E.printstacktrace ();
}

}

Public Fileitem Getuploadfileitem (list<fileitem> List) {
for (Fileitem fileitem:list) {
if (!fileitem.isformfield ()) {
return fileitem;
}
}
return null;
}

Public String Getuploadfilename (Fileitem item) {
Get path name
String value = Item.getname ();
Index to the last backslash
int start = Value.lastindexof ("/");
Intercept the string name of the uploaded file, plus 1 is to remove the backslash,
String filename = value.substring (start + 1);

return filename;
}

/**
* @see Httpservlet#dopost (httpservletrequest request, HttpServletResponse
* Response)
*/
public void DoPost (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {
This.doget (request, response);
}

}

(4) Ajax for the Web interface:

<script type= "Text/javascript" >
$ (function () {
Upload image
New Ajaxupload (' #addLabProdPic ', {
Action: ' Upload ',
Name: ' Picfile ',
Responsetype: ' JSON ',
Onsubmit:function (file, ext) {
if (ext &&/^ (jpg|png|bmp) $/.test (Ext.tolowercase ())) {
This.setdata ({
' Picname ': File
});
} else {
Alert ("Please upload the image formatted as Jpg|png|bmp!") ");
return false;
}
},
Oncomplete:function (file,response) {
if (response.error) {
alert (response.error);
Return
}
$ (' #viewImg '). attr (' src ', response.picurl);
$ (' #viewImgSRC '). Val (Response.picurl); Show pictures with the
}
});
})
</script>

2. Show pictures

Front-End Code:

Back-end Programs:

Out.println (" '); TPWZ is the corresponding field in the database

Back-end full code:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
pageencoding= "Utf-8"%>
<%@ page import= "java.sql.*"%>
<%@ page import= "java.text.*"%>
<%@ page import= "java.util.*"%>
<%@ page import= "java.io.*"%>
<%@ page import= "org.apache.commons.fileupload.*"%>
<%@ page import= "javax.servlet.*"%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<jsp:usebean id= "db" scope= "page" class= "Fujin. DbConnection "/>
<jsp:usebean id= "Upload" scope= "page" class= "upload. Uploadprocessorservlet "/>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<link rel= "stylesheet" type= "Text/css" href= "Css/normalize.css"/>
<link rel= "stylesheet" type= "Text/css" href= "Css/default.css" >
<link rel= "stylesheet" type= "Text/css" href= "Fonts/font-awesome-4.3.0/css/font-awesome.min.css"/>
<link rel= "stylesheet" type= "Text/css" href= "Css/style2.css"/>
<script src= "Js/modernizr.custom.js" ></script>
<title> Event Information </title>
<body>
<%
Db.opendb ();


int i=0,j=1,k; I record activity id,j record number of entries id,k is a return parameter of the comparison string
String[] Hdmc=new string[1000]; Activity name
Int[] Bh=new int[1000]; Number
String[] Fqr=new string[1000]; Sponsor
String[] Bmsj=new string[1000]; Registration time
String[] Zjsj=new string[1000]; Closing Time of registration
String[] Hdsj=new string[1000]; Event time
String[] Jssj=new string[1000]; End time
String[] Tpwz=new string[1000]; Picture location
String[] Dzwz=new string[1000]; Approximate position
String[] Xxwz=new string[1000]; Detailed location
String[] Hdlb=new string[1000]; Activity category
String[] Yldh=new string[1000]; Reserved phone
String[] Hdsm=new string[1000]; Event description
String[] Cjsj=new string[1000]; Creation time
Int[] Bmrs=new int[1000]; Number of applicants
String now=new SimpleDateFormat ("Yyyy-mm-dd"). Format (Calendar.getinstance (). GetTime ());//Current time
String sql= "SELECT * from Huodongfaqi where Jssj>now ()";
String sql1= "Select Bh,count (*) from Canyubiao GROUP by BH";
ResultSet rs=db.executequery (SQL);
while (Rs.next ())
{
Hdmc[i]=rs.getstring ("HDMC");
Bh[i]=rs.getint ("BH");
Fqr[i]=rs.getstring ("FQR");
Bmsj[i]=rs.getstring ("BMSJ");
Zjsj[i]=rs.getstring ("ZJSJ");
Hdsj[i]=rs.getstring ("HDSJ");
Jssj[i]=rs.getstring ("JSSJ");
Tpwz[i]=rs.getstring ("Tpwz");
Dzwz[i]=rs.getstring ("Dzwz");
Xxwz[i]=rs.getstring ("Xxwz");
Hdlb[i]=rs.getstring ("hdlb");
Yldh[i]=rs.getstring ("Yldh");
Hdsm[i]=rs.getstring ("HDSM");
Cjsj[i]=rs.getstring ("CJSJ");
i++;
}
i--; Keep the I and ID numbers consistent

Rs.close ();
ResultSet rs1=db.executequery (SQL1);
while (Rs1.next ())
{
Bmrs[j]=rs1.getint ("Count (*)");
j + +;
}
for (int length=i;length>=0;length--)
{
Out.println ("<body class= ' container ' >");

Out.println ("<div>");
Out.println ("<section class= ' grid ' >");
Out.println ("<a class= ' grid__item ' href= ' xiangxihuodong.jsp?id=" +bh[length]+ ">");
Out.println ("

Out.println ("<div class= ' loader ' ></div>");
Out.println ("<span class= category" > Activity type: "+hdlb[length]+" </span> ");
Out.println ("<div class= ' meta Meta--preview ' >");
Out.println (" ');
Out.println ("<span class= ' meta__date ' ><i class= ' fa fa-calendar-o ' ></i> registration time:" +bmsj[length]+ "< /SPAN> ");
Out.println ("<br/>");
Out.println ("<span class= ' meta__date ' > &nbsp;&nbsp;&nbsp;&nbsp; location:" +dzwz[length]+ "</ Span> ");
Out.println ("<span class= ' meta__reading-time ' ><i class= ' fa fa-clock-o ' ></i> registration number:" +bmrs[length]+ "</span>");
Out.println ("</div>");
Out.println ("</a>");
Out.println ("</section>");

Out.println ("</div>");
Out.println ("</body>");

}
Rs1.close ();
Db.closedb ();
%>

</body>

Image upload and display of mobile development

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.