编程行数:1500行
编程时长:16h
发表博客篇数:5篇
所学知识点:
一。通过JAVA实现图片上传功能:
基本思路:将提交数据的form表单通过enctype="multipart/form-data"进行数据打包处理,后台通过创建DiskFileItemFactory文件磁盘工厂进行接受,创建文件解析器ServletFileUpload upload = new ServletFileUpload(factory);通过两种不同的方式分别对普通文本数据和文件流数据进行获取,name = fileItem.getFieldName(); //普通文本数据获取 InputStream is = fileItem.getInputStream(); String filename = fileItem.getName();//文件数据获取,然后将文件数据转移到相对路径下并将其文件名存进数据库,将普通文本数据同样存进数据库,然后通过数据库获取文件名从相对路径下调用即可
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
DAO层函数
package Dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import DBcon.db;
import Entity.FileUploadUtils;
public class Dao {
public boolean add(FileUploadUtils utils) {
String sql = "insert into photo1(id,name) values('" + utils.getId() + "','" + utils.getPhotoname() + "')";
//创建数据库链接
Connection conn = db.getConn();
Statement state = null;
boolean f = false;
int a = 0 ;
try {
state = conn.createStatement();
a = state.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭z 连接
db.close(state, conn);
}
if (a > 0) {
f = true;
}
return f;
}
public ResultSet getAllRs(){
String sql="SELECT * from photo1 ORDER BY xuhao desc";
Connection conn = db.getConn();
ResultSet rs = null;
try{
Statement state = conn.createStatement();
rs=state.executeQuery(sql);
}
catch(SQLException e){
e.printStackTrace();
}
return rs;
}
}
Servlet///////
package Servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
import Dao.Dao;
import Entity.FileUploadUtils;
/**文件上传servlet
* Servlet implementation class imgServlet
*/
@WebServlet("/imgServlet")
public class imgServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public imgServlet() {
super();
// TODO Auto-generated constructor stub
}
Dao dao = new Dao();
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//1乱码
// response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String path = request.getServletContext().getRealPath("/upload");// /指的是项目路径
System.out.println(path);
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();//创建
}
//2处理文件上传
//2.1创建磁盘文件工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// factory.setSizeThreshold(1024*100);//使用缓存,设置缓存大小100k 默认10k
//设置缓存位置
// factory.setRepository(new File("d:\\..."));
//创建文件解析器
ServletFileUpload upload = new ServletFileUpload(factory);
//判断是否为多分布表单
if(!upload.isMultipartContent(request)) {
return;
}
//解析
upload.setHeaderEncoding("utf-8");//解决文件名中文乱码
//控制单独文件大小2M
// upload.setFileSizeMax(1024*1024*2);
// //控制总文件大小
// upload.setSizeMax(1024*1025*50);
String name = null;
String value = null;
String filenameNow = null;
String ext = null;
String newfilename = null;
try {
List fileItems = upload.parseRequest(request);//表单中数据
if(fileItems!=null) {
for(FileItem fileItem : fileItems) {
//处理表单中的普通数据数据
if(fileItem.isFormField()) {
name = fileItem.getFieldName();
if(!name.equals("submit")) {
value = fileItem.getString("utf-8");//注意乱码
}
System.out.println( name + "....." + value);
}else {//处理文件数据
//流处理
InputStream is = fileItem.getInputStream();
String filename = fileItem.getName();
String temp[]=filename.split("\\\\");
filenameNow = temp[temp.length-1];
//如果满zu上传文件
if(filenameNow==null||filenameNow.trim().equals("")) {
continue;
}
//控制上传文件的类型
ext = filenameNow.substring(filenameNow.lastIndexOf(".")+1);
List acceptExts = new ArrayList();
acceptExts.add("jpg");
acceptExts.add("png");
if(!acceptExts.contains(ext)) {
response.getWriter().write(filenameNow+"不支持此格式文件上传");
continue;
}
newfilename = FileUploadUtils.getNewFilename(filenameNow);
FileOutputStream fos = new FileOutputStream(dir+"\\"+newfilename);
byte[] buf = new byte[1024*4];
int len = 0;
while((len=is.read(buf))!=-1) {
fos.write(buf,0,len);
}
fos.close();
is.close();
response.getWriter().write(filenameNow+"LOAD SUCCESS!");
}
}
FileUploadUtils utils = new FileUploadUtils(value,newfilename);
if(dao.add(utils)) {
request.setAttribute("message", "添加成功!");
request.getRequestDispatcher("addresult.jsp").forward(request, response);
}else {
request.setAttribute("message", "图书名称重复,请重新输入!");
request.getRequestDispatcher("add.jsp").forward(request, response);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
实体层函数:
package Entity;
import java.util.UUID;
public class FileUploadUtils {
private String id;
private String photoname;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPhotoname() {
return photoname;
}
public void setPhotoname(String photoname) {
this.photoname = photoname;
}
public static String getNewFilename(String oldfilename) {
String uuid = UUID.randomUUID().toString();//全球通用唯一表示
System.out.println(uuid);
return uuid+"_"+oldfilename;
}
public FileUploadUtils(String id, String name) {
this.id = id;
this.photoname = name;
}
}
显示图片
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
Insert title here
照片名称
照片显示
<%
ResultSet rs=dao.getAllRs();
if(rs==null){
%>
没有记录显示!
<%
}
else{
if(rs.next()){
%>
222222
<%=rs.getString("id") %>
" width="150px";height="100px">
<%
}
if(rs.next()){
%>
4444
<%=rs.getString("id") %>
" width="150px";height="100px">
<%
}
if(rs.next()){
%>
uuuuu
<%=rs.getString("id") %>
" width="150px";height="100px">
<%
}
}
%>
**********************
**********************
运行截图:
二。通过PHP代码实现图片上传并显示,其主要思路是先将form表单通过 enctype="multipart/form-data"进行格式化打包,其后台的普通文本数据用POST取,而文件数据用FILE取,将获取的图片转移到一个新的相对路径下存储,将图片的名字存进数据库,来实现图片的存储。
Document
query($sql)) {
echo "";
//header() 函数向客户端发送原始的 HTTP 报头。
} else {
echo "添加失败";
}
?>