求java上传图片、文件(音乐,压缩文件,文本之类的)代码
求java上传图片、文件(音乐,压缩文件,文本之类的)代码
额是新手,请前辈指教~
希望得到详细代码,能给整个例子额感激不尽~
[解决办法]
贴段代码给你。要给分哦!!
servlet
import java.io.BufferedInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.util.Calendar;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Upload extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); javax.servlet.ServletInputStream inputStream = request.getInputStream(); int position=-1; FileOutputStream outputStream = null; byte[] buffer = new byte[1024]; position=inputStream.readLine(buffer, 0, buffer.length); String breakStr = ""; String objRef = ""; if(position!=-1){ breakStr = new String(buffer,0,28); objRef = new String(buffer,29,position); System.out.println(breakStr); System.out.println(objRef); } position = inputStream.readLine(buffer, 0, buffer.length); String upFileName = ""; String fileType = ""; if(position!=-1){ upFileName = new String(buffer,0,position); System.out.println(upFileName); int fileNamePosition = 0; if((fileNamePosition=upFileName.indexOf("filename=\""))!=-1){ fileType=upFileName.substring(fileNamePosition).split("\"")[1]; outputStream=new FileOutputStream("d://Upload" + Calendar.getInstance().getTimeInMillis()+ fileType); } } position = inputStream.readLine(buffer, 0, buffer.length); String type=""; if(position!=-1){ type = new String(buffer,0,position); System.out.println(type); } String isBreakStr=""; inputStream.readLine(buffer, 0, buffer.length); while((position=inputStream.readLine(buffer, 0, buffer.length))!=-1){ isBreakStr = new String(buffer, 0, position); if (isBreakStr.length() > 28 && isBreakStr.substring(0, 28).equals(breakStr)) { break; } outputStream.write(buffer, 0, position); } outputStream.flush(); inputStream.close(); outputStream.close(); }}
[解决办法]
有一个upload有关的java类包,里面有页面代码和几个java类。还有一个上传图片的例子。跟上传文件差不多。楼主要不要。
[解决办法]
java上传功能源码http://download.csdn.net/source/970570
javabean实现上传功能源码http://download.csdn.net/source/970479
仿163网盘无刷新多附件上传源码http://download.csdn.net/source/1037046
[解决办法]
SmartUpload实现上传:
smartupload上传文件中应该注意的地方是表单中<form enctype="multipart/form-data" name="form1" action="zhbupload" method="post" >的enctype="multipart/form-data"是必须的,还有用了jspSmartupload以后jsp中的request就失效了,要用Smartupload中的Request myrequest = null;mySmartUpload.upload();myrequest = mySmartUpload.getRequest();通过myrequest来获取表单中除了上传文件的表单的其他内容!!还有数据库里面file的数据类型一定要是LongBlob!!package Action;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.PrintWriter;import java.sql.PreparedStatement;import java.util.Calendar;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import Other.DataBaseConnection;import com.jspsmart.upload.Request;import com.jspsmart.upload.SmartUpload;public class Picupload extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gb2312"); PrintWriter out = response.getWriter(); SmartUpload mySmartUpload = new SmartUpload(); Request myrequest = null; String username = "", pwd = ""; // long file_size_max = 4000000; String ext = ""; String url = "touxiang\\"; // 应保证在根目录中有此目录的存在 // 初始化 mySmartUpload.initialize(this.getServletConfig(), request, response); // 只允许上载此类文件 try { mySmartUpload.setAllowedFilesList("jpg,gif"); // 上载文件 mySmartUpload.upload(); myrequest = mySmartUpload.getRequest(); } catch (Exception e) { out.print("<script>"); out .println("alert('只允许上传.jpg和.gif类型图片文件!');window.location='user_register.jsp';"); out.print("</script>"); } try { com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile( 0); int count = 0; if (myFile.isMissing()) { out.print("<script>"); out.println("alert('请至少选择一个要上传的文件!');window.location='user_register.jsp';"); out.print("</script>"); } else { // String myFileName=myFile.getFileName(); //取得上载的文件的文件名 out.println("正在上传文件,请等待。。。。。"); HttpSession session = request.getSession(); for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) { myFile = mySmartUpload.getFiles().getFile(i); if (myFile.isMissing()) continue; ext = myFile.getFileExt(); // 取得后缀名 int file_size = myFile.getSize(); // 取得文件的大小 String saveurl = ""; // 更改文件名,取得当前上传时间的毫秒数值 Calendar calendar = Calendar.getInstance(); String filename = String .valueOf(calendar.getTimeInMillis()); saveurl = request.getRealPath("\\") + url; saveurl += filename + "." + ext; // 最终文件的保存路径 System.out.println(saveurl); myFile.saveAs(saveurl, mySmartUpload.SAVE_PHYSICAL); username = myrequest.getParameter("username"); pwd = myrequest.getParameter("pwd"); PreparedStatement pstmt = null; DataBaseConnection dbc = null; dbc = new DataBaseConnection(); FileInputStream fis; File file; file = new File(saveurl); fis = new FileInputStream(file); pstmt = dbc .getConnection() .prepareStatement( "insert into user(username,pwd,pic,userid) values(?,?,?,?)"); pstmt.setString(1, username); pstmt.setString(2, pwd); pstmt.setBinaryStream(3, fis, (int) file.length()); pstmt.setInt(4, 1); System.out.println("success inserted user into database"); pstmt.execute(); pstmt.close(); dbc.close(); } out.print("<script>"); out.print("alert('上传成功');"); out.print("window.location='login.jsp'"); out.print("</script>"); } } catch (Exception e) { e.toString(); } }}
[解决办法]
SmartUpload实现上传:
smartupload上传文件中应该注意的地方是表单中<form enctype="multipart/form-data" name="form1" action="zhbupload" method="post" >的enctype="multipart/form-data"是必须的,还有用了jspSmartupload以后jsp中的request就失效了,要用Smartupload中的Request myrequest = null;mySmartUpload.upload();myrequest = mySmartUpload.getRequest();通过myrequest来获取表单中除了上传文件的表单的其他内容!!还有数据库里面file的数据类型一定要是LongBlob!!package Action;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.PrintWriter;import java.sql.PreparedStatement;import java.util.Calendar;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import Other.DataBaseConnection;import com.jspsmart.upload.Request;import com.jspsmart.upload.SmartUpload;public class Picupload extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gb2312"); PrintWriter out = response.getWriter(); SmartUpload mySmartUpload = new SmartUpload(); Request myrequest = null; String username = "", pwd = ""; // long file_size_max = 4000000; String ext = ""; String url = "touxiang\\"; // 应保证在根目录中有此目录的存在 // 初始化 mySmartUpload.initialize(this.getServletConfig(), request, response); // 只允许上载此类文件 try { mySmartUpload.setAllowedFilesList("jpg,gif"); // 上载文件 mySmartUpload.upload(); myrequest = mySmartUpload.getRequest(); } catch (Exception e) { out.print("<script>"); out .println("alert('只允许上传.jpg和.gif类型图片文件!');window.location='user_register.jsp';"); out.print("</script>"); } try { com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile( 0); int count = 0; if (myFile.isMissing()) { out.print("<script>"); out.println("alert('请至少选择一个要上传的文件!');window.location='user_register.jsp';"); out.print("</script>"); } else { // String myFileName=myFile.getFileName(); //取得上载的文件的文件名 out.println("正在上传文件,请等待。。。。。"); HttpSession session = request.getSession(); for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) { myFile = mySmartUpload.getFiles().getFile(i); if (myFile.isMissing()) continue; ext = myFile.getFileExt(); // 取得后缀名 int file_size = myFile.getSize(); // 取得文件的大小 String saveurl = ""; // 更改文件名,取得当前上传时间的毫秒数值 Calendar calendar = Calendar.getInstance(); String filename = String .valueOf(calendar.getTimeInMillis()); saveurl = request.getRealPath("\\") + url; saveurl += filename + "." + ext; // 最终文件的保存路径 System.out.println(saveurl); myFile.saveAs(saveurl, mySmartUpload.SAVE_PHYSICAL); username = myrequest.getParameter("username"); pwd = myrequest.getParameter("pwd"); PreparedStatement pstmt = null; DataBaseConnection dbc = null; dbc = new DataBaseConnection(); FileInputStream fis; File file; file = new File(saveurl); fis = new FileInputStream(file); pstmt = dbc .getConnection() .prepareStatement( "insert into user(username,pwd,pic,userid) values(?,?,?,?)"); pstmt.setString(1, username); pstmt.setString(2, pwd); pstmt.setBinaryStream(3, fis, (int) file.length()); pstmt.setInt(4, 1); System.out.println("success inserted user into database"); pstmt.execute(); pstmt.close(); dbc.close(); } out.print("<script>"); out.print("alert('上传成功');"); out.print("window.location='login.jsp'"); out.print("</script>"); } } catch (Exception e) { e.toString(); } }}
[解决办法]
SmartUpload实现上传:
package Action;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.PrintWriter;import java.sql.PreparedStatement;import java.util.Calendar;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import Other.DataBaseConnection;import com.jspsmart.upload.Request;import com.jspsmart.upload.SmartUpload;public class Picupload extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gb2312"); PrintWriter out = response.getWriter(); SmartUpload mySmartUpload = new SmartUpload(); Request myrequest = null; String username = "", pwd = ""; // long file_size_max = 4000000; String ext = ""; String url = "touxiang\\"; // 应保证在根目录中有此目录的存在 // 初始化 mySmartUpload.initialize(this.getServletConfig(), request, response); // 只允许上载此类文件 try { mySmartUpload.setAllowedFilesList("jpg,gif"); // 上载文件 mySmartUpload.upload(); myrequest = mySmartUpload.getRequest(); } catch (Exception e) { out.print("<script>"); out .println("alert('只允许上传.jpg和.gif类型图片文件!');window.location='user_register.jsp';"); out.print("</script>"); } try { com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile( 0); int count = 0; if (myFile.isMissing()) { out.print("<script>"); out.println("alert('请至少选择一个要上传的文件!');window.location='user_register.jsp';"); out.print("</script>"); } else { // String myFileName=myFile.getFileName(); //取得上载的文件的文件名 out.println("正在上传文件,请等待。。。。。"); HttpSession session = request.getSession(); for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) { myFile = mySmartUpload.getFiles().getFile(i); if (myFile.isMissing()) continue; ext = myFile.getFileExt(); // 取得后缀名 int file_size = myFile.getSize(); // 取得文件的大小 String saveurl = ""; // 更改文件名,取得当前上传时间的毫秒数值 Calendar calendar = Calendar.getInstance(); String filename = String .valueOf(calendar.getTimeInMillis()); saveurl = request.getRealPath("\\") + url; saveurl += filename + "." + ext; // 最终文件的保存路径 System.out.println(saveurl); myFile.saveAs(saveurl, mySmartUpload.SAVE_PHYSICAL); username = myrequest.getParameter("username"); pwd = myrequest.getParameter("pwd"); PreparedStatement pstmt = null; DataBaseConnection dbc = null; dbc = new DataBaseConnection(); FileInputStream fis; File file; file = new File(saveurl); fis = new FileInputStream(file); pstmt = dbc .getConnection() .prepareStatement( "insert into user(username,pwd,pic,userid) values(?,?,?,?)"); pstmt.setString(1, username); pstmt.setString(2, pwd); pstmt.setBinaryStream(3, fis, (int) file.length()); pstmt.setInt(4, 1); System.out.println("success inserted user into database"); pstmt.execute(); pstmt.close(); dbc.close(); } out.print("<script>"); out.print("alert('上传成功');"); out.print("window.location='login.jsp'"); out.print("</script>"); } } catch (Exception e) { e.toString(); } }}
[解决办法]
common-fileupload上传的工具类,在Servlet中使用此工具类可参照main()方法的用法
import java.io.File;import java.io.IOException;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;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.FileUploadBase.SizeLimitExceededException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import com.zzxy.common.MISException;public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; // 保存普通form表单域 private Map<String, String> parameters; // 保存上传的文件 private Map<String, FileItem> files; // 上传文件的最大长度,-1表示不限制上传文件最大长度 100 * 1024 * 1024 private long maxSize = -1; // 允许上传的文件格式的列表 private String[] allowedExt = new String[] { ".jpg", ".jpeg", ".gif", ".txt", ".doc", ".docx", ".bmp", ".avi", ".chm", ".pdf", ".html", ".htm", ".swf", ".rar", ".zip", ".xls", ".ppt" }; // 设置上传文件时用于临时存放文件的内存大小,多于的部分将临时存在硬盘 private int sizeThreshold = DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD; // 设置字符编码为UTF-8, 这样支持汉字显示。当读取上传表单的各部分时会用到该encoding private String encoding = "utf-8"; // 上传文件临时目录 private String repositoryPath = "d:\\temp\\"; /** * <p> * Title: FileUpload构造函数 * </p> * <p> * Description: 上传文件的构造函数,上传临时文件为D:\temp\,不限上传文件大小,不限后缀名 * </p> */ public FileUpload() { super(); // TODO Auto-generated constructor stub } /** * <p> * Title: FileUpload构造函数 * </p> * <p> * Description: 上传文件的构造函数,上传文件格式不限制 * </p> * * @param maxSize * 允许上传的文件最大长度 * @param repositoryPath * 上传文件的临时文件目录 */ public FileUpload(long maxSize, String repositoryPath) { super(); this.maxSize = maxSize; this.repositoryPath = repositoryPath; } /** * <p> * Title: FileUpload构造函数 * </p> * <p> * Description: 上传文件的构造函数 * </p> * * @param maxSize * 允许上传的文件最大长度 * @param allowedExt * 允许上传的后缀名 * @param repositoryPath * 上传文件的临时文件目录 */ public FileUpload(long maxSize, String[] allowedExt, String repositoryPath) { super(); this.maxSize = maxSize; this.allowedExt = allowedExt; this.repositoryPath = repositoryPath; } /** * <p> * Title: FileUpload构造函数 * </p> * <p> * Description: 上传文件的构造函数,上传文件大小不限制 * </p> * * @param allowedExt * 允许上传的后缀名 * @param repositoryPath * 上传文件的临时文件目录 */ public FileUpload(String[] allowedExt, String repositoryPath) { super(); this.allowedExt = allowedExt; this.repositoryPath = repositoryPath; } /** * @方法名: getFileName * @作者 倪志鹏 * @功能:得到上传文件名称 * @param item * @return * @返回类型 String */ public String getFileName(FileItem item) { String fileName = item.getName(); fileName = fileName.replace("\\", "/").substring( fileName.lastIndexOf("/") + 1); return fileName; } /** * @方法名: getExtension * @作者 倪志鹏 * @功能:得到上传文件的后缀名(include ".") * @param item * @return * @返回类型 String */ public String getExtension(FileItem item) { String strExtension = getFileName(item).substring( getFileName(item).lastIndexOf(".")); return strExtension; } /** * @方法名: checkExtension * @作者 倪志鹏 * @功能:检查后缀名是否合法上传的文件(include ".") * @param item * @return * @返回类型 boolean */ public boolean checkExtension(String strExtension) { boolean flag = true; // 拒绝接受规定文件格式之外的文件类型 int allowFlag = 0; int allowedExtCount = allowedExt.length; for (; allowFlag < allowedExtCount; allowFlag++) { if (allowedExt[allowFlag].equals(strExtension)) break; } if (allowFlag == allowedExtCount) { String strTemp = "<script>alert(\"请上传以下类型的文件:"; for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) { strTemp += "*." + allowedExt[allowFlag] + " "; } strTemp += "\");</script>"; System.out.println("strTemp----End--->" + strTemp); // out.print(strTemp); flag = false; } return flag; }
[解决办法]
public void parse(HttpServletRequest request, HttpServletResponse response) throws Exception { parameters = new HashMap<String, String>(); files = new HashMap<String, FileItem>(); response.setContentType("text/html"); // 设置字符编码为UTF-8, 这样支持汉字显示 response.setCharacterEncoding("UTF-8"); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置上传文件时用于临时存放文件的内存大小,多于的部分将临时存在硬盘 factory.setSizeThreshold(sizeThreshold); java.io.File tempFolder = new java.io.File(repositoryPath); if (!tempFolder.exists()) tempFolder.mkdirs(); // 设置存放临时文件的目录 factory.setRepository(tempFolder); // 用以上工厂实例化上传组件 ServletFileUpload upload = new ServletFileUpload(factory); // 设置最大上传尺寸 upload.setSizeMax(maxSize); // 设置上传文件编码 upload.setHeaderEncoding(encoding); // PrintWriter out = response.getWriter(); // 从request得到 所有 上传域的列表 List fileList = null; try { fileList = upload.parseRequest(request); } catch (FileUploadException e) {// 处理文件尺寸过大异常 if (e instanceof SizeLimitExceededException) { // out.println("<script>alert(\"文件尺寸超过规定大小:" + maxSize // + "字节\");</script>"); throw new MISException("文件尺寸超过规定大小:" + maxSize + "字节!"); } e.printStackTrace(); } // 没有文件上传 if (fileList == null || fileList.size() == 0) { // out.println("<script>alert(\"请选择上传文件\");</script>"); throw new MISException("请选择上传文件!"); } // 得到所有上传的文件 Iterator iterator = fileList.iterator(); // 循环处理所有文件 while (iterator.hasNext()) { FileItem fileItem = null; String path = null; long size = 0; // 得到当前文件 fileItem = (FileItem) iterator.next(); if (fileItem.isFormField()) { String fieldName = fileItem.getFieldName(); String value = fileItem.getString(); parameters.put(fieldName, value); } else { String fieldName = fileItem.getFieldName(); files.put(fieldName, fileItem); // 得到文件的完整路径 path = fileItem.getName(); // 得到文件的大小 size = fileItem.getSize(); if ("".equals(path) || size == 0) { // out.println("<script>alert(\"请选择上传文件\");</script>"); throw new MISException("请选择上传文件!"); } // 得到去除路径的文件名 // String t_name = getFileName(fileItem); // 得到文件的扩展名(无扩展名时将得到全名) String t_ext = getExtension(fileItem); // System.out.println(""+t_ext); // 判断文件后缀名是否为合法上传文件 if (!checkExtension(t_ext)) { String strTip = "请上传以下类型的文件:"; for (int allowFlag = 0; allowFlag < allowedExt.length; allowFlag++) { strTip += "*." + allowedExt[allowFlag] + " "; } throw new MISException(strTip); } } } } /** * @方法名: rename * @作者 倪志鹏 * @功能:对文件进行重命名 * @param oldName * 老文件名 * @param newName * 新文件名 * @return * @返回类型 File */ private File rename(String oldName, String newName) { int dot = oldName.lastIndexOf("."); String ext = null; if (dot != -1) { ext = oldName.substring(dot); // includes "." } File f = new File(newName + ext); createNewFile(f); return f; } /** * @方法名: createNewFile * @作者 倪志鹏 * @功能:创建新的文件 * @param f * @return * @返回类型 boolean */ private boolean createNewFile(File f) { try { return f.createNewFile(); } catch (IOException ignored) { return false; } } /** * @return the maxPostSize */ public long getMaxSize() { return maxSize; } /** * @param maxSize * 要设置的 maxSize */ public void setMaxSize(long maxSize) { this.maxSize = maxSize; } /** * @return the allowedExt */ public String[] getAllowedExt() { return allowedExt; } /** * @param allowedExt * 要设置的 allowedExt */ public void setAllowedExt(String[] allowedExt) { this.allowedExt = allowedExt; } /** * @return the sizeThreshold */ public int getSizeThreshold() { return sizeThreshold; } /** * @param sizeThreshold * 要设置的 sizeThreshold */ public void setSizeThreshold(int sizeThreshold) { this.sizeThreshold = sizeThreshold; } /** * @return the encoding */ public String getEncoding() { return encoding; } /** * @param encoding * 要设置的 encoding */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * @return the repositoryPath */ public String getRepositoryPath() { return repositoryPath; } /** * @param repositoryPath * 要设置的 repositoryPath */ public void setRepositoryPath(String repositoryPath) { this.repositoryPath = repositoryPath; } public static void main(String[] args, HttpServletRequest request, HttpServletResponse response) throws Exception { FileUpload fileUpload = new FileUpload(); fileUpload.parse(request, response); System.out.println(fileUpload.parameters.get("possess")); Iterator iterator = fileUpload.files.values().iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); String fileName = fileUpload.getFileName(item); String strExtension = fileUpload.getExtension(item); // fileUpload.rename(oldName, newName); File file = new File("/root/upload/" + fileName); try { item.write(file); } catch (Exception e) { e.printStackTrace(); } } } /** * @return the parameters */ public Map<String, String> getParameters() { return parameters; } /** * @param parameters * 要设置的 parameters */ public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } /** * @return the files */ public Map<String, FileItem> getFiles() { return files; } /** * @param files * 要设置的 files */ public void setFiles(Map<String, FileItem> files) { this.files = files; }}