文件管理 · 2022年8月13日

java文件上传组件|java上传文件怎么实现的

⑴ java怎么用commons-fileupload实现上传文件

文件上传步骤:1.导入jar包common-fileupload.jarcommon-io.jar2.上传jsp页面编辑<body><formaction="${pageContext.request.contextPath}/servlet/UploadHandleServlet"enctype="multipart/form-data"method="post">上传用户:<inputtype="text"name="username"><br/>上传文件1:<inputtype="file"name="file1"><br/>上传文件2:<inputtype="file"name="file2"><br/><inputtype="submit"value="提交"></form></body>3.消息提示页面(成功or失败)<body>${message}</body>4.处理文件上传的servlet编写importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.util.List;importjava.util.UUID;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.commons.fileupload.FileItem;importorg.apache.commons.fileupload.FileUploadBase;importorg.apache.commons.fileupload.ProgressListener;importorg.apache.commons.fileupload.disk.DiskFileItemFactory;importorg.apache.commons.fileupload.servlet.ServletFileUpload;{publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全StringsavePath=this.getServletContext().getRealPath("/WEB-INF/upload");//上传时生成的临时文件保存目录StringtempPath=this.getServletContext().getRealPath("/WEB-INF/temp");FiletmpFile=newFile(tempPath);if(!tmpFile.exists()){//创建临时目录tmpFile.mkdir();}//消息提示Stringmessage="";try{//使用Apache文件上传组件处理文件上传步骤://1、创建一个DiskFileItemFactory工厂DiskFileItemFactoryfactory=newDiskFileItemFactory();//设置工厂的缓冲区的大小,当上传的文件大小超过缓冲区的大小时,就会生成一个临时文件存放到指定的临时目录当中。factory.setSizeThreshold(1024*100);//设置缓冲区的大小为100KB,如果不指定,那么缓冲区的大小默认是10KB//设置上传时生成的临时文件的保存目录factory.setRepository(tmpFile);//2、创建一个文件上传解析器ServletFileUploapload=newServletFileUpload(factory);//监听文件上传进度upload.setProgressListener(newProgressListener(){publicvoipdate(longpBytesRead,longpContentLength,intarg2){System.out.println("文件大小为:"+pContentLength+",当前已处理:"+pBytesRead);/***文件大小为:14608,当前已处理:4096文件大小为:14608,当前已处理:7367文件大小为:14608,当前已处理:11419文件大小为:14608,当前已处理:14608*/}});//解决上传文件名的中文乱码upload.setHeaderEncoding("UTF-8");//3、判断提交上来的数据是否是上传表单的数据if(!ServletFileUpload.isMultipartContent(request)){//按照传统方式获取数据return;}//设置上传单个文件的大小的最大值,目前是设置为1024*1024字节,也就是1MBupload.setFileSizeMax(1024*1024);//设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10MBupload.setSizeMax(1024*1024*10);//4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项List<FileItem>list=upload.parseRequest(request);for(FileItemitem:list){//如果fileitem中封装的是普通输入项的数据if(item.isFormField()){Stringname=item.getFieldName();//解决普通输入项的数据的中文乱码问题Stringvalue=item.getString("UTF-8");//value=newString(value.getBytes("iso8859-1"),"UTF-8");System.out.println(name+"="+value);}else{//如果fileitem中封装的是上传文件//得到上传的文件名称,Stringfilename=item.getName();System.out.println(filename);if(filename==null||filename.trim().equals("")){continue;}//注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如:c:a1.txt,而有些只是单纯的文件名,如:1.txt//处理获取到的上传文件的文件名的路径部分,只保留文件名部分filename=filename.substring(filename.lastIndexOf("\")+1);//得到上传文件的扩展名StringfileExtName=filename.substring(filename.lastIndexOf(".")+1);//如果需要限制上传的文件类型,那么可以通过文件的扩展名来判断上传的文件类型是否合法System.out.println("上传的文件的扩展名是:"+fileExtName);//获取item中的上传文件的输入流InputStreamin=item.getInputStream();//得到文件保存的名称StringsaveFilename=makeFileName(filename);//得到文件的保存目录StringrealSavePath=makePath(saveFilename,savePath);//创建一个文件输出流FileOutputStreamout=newFileOutputStream(realSavePath+"\"+saveFilename);//创建一个缓冲区bytebuffer[]=newbyte[1024];//判断输入流中的数据是否已经读完的标识intlen=0;//循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据while((len=in.read(buffer))>0){//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath+"\"+filename)当中out.write(buffer,0,len);}//关闭输入流in.close();//关闭输出流out.close();//删除处理文件上传时生成的临时文件//item.delete();message="文件上传成功!";}}}catch(FileUploadBase.){e.printStackTrace();request.setAttribute("message","单个文件超出最大值!!!");request.getRequestDispatcher("/message.jsp").forward(request,response);return;}catch(FileUploadBase.SizeLimitExceededExceptione){e.printStackTrace();request.setAttribute("message","上传文件的总的大小超出限制的最大值!!!");request.getRequestDispatcher("/message.jsp").forward(request,response);return;}catch(Exceptione){message="文件上传失败!";e.printStackTrace();}request.setAttribute("message",message);request.getRequestDispatcher("/message.jsp").forward(request,response);}privateStringmakeFileName(Stringfilename){//2.jpg//为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名returnUUID.randomUUID().toString()+"_"+filename;}privateStringmakePath(Stringfilename,StringsavePath){//得到文件名的hashCode的值,得到的就是filename这个字符串对象在内存中的地址inthashcode=filename.hashCode();intdir1=hashcode&0xf;//0–15intdir2=(hashcode&0xf0)>>4;//0-15//构造新的保存目录Stringdir=savePath+"\"+dir1+"\"+dir2;//upload23upload35if(!file.exists()){file.mkdirs();}returndir;}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doGet(request,response);}}5.编写web.xml文件(servlet的映射配置)<servlet><servlet-name>UploadHandleServlet</servlet-name><servlet-class>me.gacl.web.controller.UploadHandleServlet</servlet-class></servlet><servlet-mapping><servlet-name>UploadHandleServlet</servlet-name><url-pattern>/servlet/UploadHandleServlet</url-pattern></servlet-mapping>注:网上看到的,出处找不到了,望见谅!!

⑵ java上传文件怎么实现的

common-fileupload是jakarta项目组开发的一个功能很强大的上传文件组件

下面先介绍上传文件到服务器(多文件上传):

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

import java.util.regex.*;

import org.apache.commons.fileupload.*;

public class upload extends HttpServlet {

private static final String CONTENT_TYPE = "text/html; charset=GB2312";

//Process the HTTP Post request

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType(CONTENT_TYPE);

PrintWriter out=response.getWriter();

try {

DiskFileUpload fu = new DiskFileUpload();

// 设置允许用户上传文件大小,单位:字节,这里设为2m

fu.setSizeMax(2*1024*1024);

// 设置最多只允许在内存中存储的数据,单位:字节

fu.setSizeThreshold(4096);

// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

fu.setRepositoryPath("c://windows//temp");

//开始读取上传信息

List fileItems = fu.parseRequest(request);

// 依次处理每个上传的文件

Iterator iter = fileItems.iterator();

//正则匹配,过滤路径取文件名

String regExp=".+////(.+)$";

//过滤掉的文件类型

String[] errorType={".exe",".com",".cgi",".asp"};

Pattern p = Pattern.compile(regExp);

while (iter.hasNext()) {

FileItem item = (FileItem)iter.next();

//忽略其他不是文件域的所有表单信息

if (!item.isFormField()) {

String name = item.getName();

long size = item.getSize();

if((name==null||name.equals("")) && size==0)

continue;

Matcher m = p.matcher(name);

boolean result = m.find();

if (result){

for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){

if (m.group(1).endsWith(errorType[temp])){

throw new IOException(name+": wrong type");

}

}

try{

//保存上传的文件到指定的目录

//在下文中上传文件至数据库时,将对这里改写

item.write(new File("d://" + m.group(1)));

out.print(name+" "+size+"");

}

catch(Exception e){

out.println(e);

}

}

else

{

throw new IOException("fail to upload");

}

}

}

}

catch (IOException e){

out.println(e);

}

catch (FileUploadException e){

out.println(e);

}

}

}

现在介绍上传文件到服务器,下面只写出相关代码:

以sql2000为例,表结构如下:

字段名:name filecode

类型: varchar image

数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");

代码如下:

。。。。。。

try{

这段代码如果不去掉,将一同写入到服务器中

//item.write(new File("d://" + m.group(1)));

int byteread=0;

//读取输入流,也就是上传的文件内容

InputStream inStream=item.getInputStream();

pstmt.setString(1,m.group(1));

pstmt.setBinaryStream(2,inStream,(int)size);

pstmt.executeUpdate();

inStream.close();

out.println(name+" "+size+" ");

}

。。。。。。

这样就实现了上传文件至数据库

⑶ java如何实现文件上传和下载的功能

import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.jspsmart.upload.*;import net.sf.json.JSONObject;import action.StudentAction;public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean result=true; SmartUpload mySmartUpload=new SmartUpload(); mySmartUpload.initialize(this.getServletConfig(), request,response); mySmartUpload.setTotalMaxFileSize(50*1024*1024);//大小限制 mySmartUpload.setAllowedFilesList("doc,docx");//后缀名限制 try { mySmartUpload.upload(); com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0); myFile.saveAs("/file/"+1+".doc");//保存目录 } catch (SmartUploadException e) { e.printStackTrace();result=false; } //*****************************// response.setContentType("text/html;charset=UTF-8"); response.setHeader("Cache-Control","no-cache"); PrintWriter out = response.getWriter(); out.print(result); out.flush(); out.close(); }}//我这是ajax方式的,不想这样,把//**********************//以下部分修改就行了//需要SmartUpload组件,去网上下个就行了,也有介绍的

⑷ java文件上传下载用哪种技术好

用commons-fileupload实现的上传文件同时提交form中的参数 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M // 允许上传的文件格式的列表 final String[] allowedExt = new String[] { "jpg", "jpeg", "gif","png" }; response.setContentType("text/html"); // 设置字符编码为UTF-8, 这样支持汉字显示 // response.setCharacterEncoding("GBK"); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactory dfif = new DiskFileItemFactory(); dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘 dfif.setRepository(new File(request.getRealPath("/") + "ImagesUploadTemp"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录 // 用以上工厂实例化上传组件 ServletFileUpload sfu = new ServletFileUpload(dfif); // 设置最大上传尺寸 sfu.setSizeMax(MAX_SIZE); PrintWriter out = response.getWriter(); // 从request得到 所有 上传域的列表 List fileList = null; try { fileList = sfu.parseRequest(request); } catch (FileUploadException e) {// 处理文件尺寸过大异常 if (e instanceof SizeLimitExceededException) { out.print("<script>alert('文件尺寸超过规定大小:" + MAX_SIZE + "字节');history.back();</script>"); return; } e.printStackTrace(); } // 没有文件上传 if (fileList == null || fileList.size() == 0) { out.print("<script>alert('请选择上传文件!');history.back();</script>"); return; } HashMap<String, String> paramMap = new HashMap<String, String>(); // 得到所有上传的文件 Iterator fileItr = fileList.iterator(); // 循环处理所有文件 FileItem fileUp= null; String path = null; while (fileItr.hasNext()) { FileItem fileItem = null; long size = 0; // 得到当前文件 fileItem = (FileItem) fileItr.next(); // 忽略简单form字段而不是上传域的文件域(<input type="text" />等) if (fileItem == null || fileItem.isFormField()) { String formname=fileItem.getFieldName();//获取form中的名字 String formcontent=fileItem.getString(); formname=new String(formname.getBytes(),"GBK"); formcontent=new String(formcontent.getBytes(),"GBK"); paramMap.put(formname, formcontent); } else{ //得到放文件的item fileUp= fileItem; // 得到文件的完整路径 path = fileItem.getName(); // 得到文件的大小 size = fileItem.getSize(); if ("".equals(path) || size == 0) { out.print("<script>alert('请选择上传文件!');history.back();</script>"); return; } } } // 得到去除路径的文件名 String t_name = path.substring(path.lastIndexOf("\\") + 1); // 得到文件的扩展名(无扩展名时将得到全名) String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1); // 拒绝接受规定文件格式之外的文件类型 int allowFlag = 0; int allowedExtCount = allowedExt.length; for (; allowFlag < allowedExtCount; allowFlag++) { if (allowedExt[allowFlag].equals(t_ext)) break; } if (allowFlag == allowedExtCount) { StringBuffer sb = new StringBuffer(); for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) sb.append("*." + allowedExt[allowFlag]); out.println("<script>alert('请上传以下类型的文件" + sb.toString() + "');history.back();</script>"); return; } long now = System.currentTimeMillis(); // 根据系统时间生成上传后保存的文件名 String prefix = String.valueOf(now); // 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下 String u_name = request.getRealPath("/") + "ImagesUploaded/" + prefix + "." + t_ext; // 相对项目路径 String file_url = request.getContextPath() + "/" + "ImagesUploaded/" + prefix + "." + t_ext; try { // 保存文件 fileUp.write(new File(u_name)); out.println("<script type='text/javascript'>parent.KE.plugin[\"image\"].insert('" +paramMap.get("id") + "', '" + file_url + "','" +paramMap.get("imgWidth") + "','" +paramMap.get("imgHeight") + "','" +paramMap.get("imgBorder") + "','" +paramMap.get("imgTitle") + "')</script>"); } catch (Exception e) { e.printStackTrace(); }

⑸ java后台文件上传到资源服务器上

package com.letv.dir.cloud.util;import com.letv.dir.cloud.controller.DirectorWatermarkController;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by xijunge on 2016/11/24 0024. */public class HttpRequesterFile { private static final Logger log = LoggerFactory.getLogger(HttpRequesterFile.class); private static final String TAG = "uploadFile"; private static final int TIME_OUT = 100 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * 上传文件到服务器 * * @param file * 需要上传的文件 * @param RequestURL * 文件服务器的rul * @return 返回响应的内容 * */ public static String uploadFile(File file, String RequestURL) throws IOException {String result = null;String BOUNDARY = "letv"; // 边界标识 随机生成 String PREFIX = "–", LINE_END = "\r\n";String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try {URL url = new URL(RequestURL);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(TIME_OUT);conn.setConnectTimeout(TIME_OUT);conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive");conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

⑹ java如何实现文件上传

public static int transFile(InputStream in, OutputStream out, int fileSize) {int receiveLen = 0;final int bufSize = 1000;try {byte[] buf = new byte[bufSize];int len = 0;while(fileSize – receiveLen > bufSize){len = in.read(buf);out.write(buf, 0, len);out.flush();receiveLen += len;System.out.println(len);}while(receiveLen < fileSize){len = in.read(buf, 0, fileSize – receiveLen);System.out.println(len);out.write(buf, 0, len);receiveLen += len;out.flush();}} catch (IOException e) {// TODO 自动生成 catch 块e.printStackTrace();}return receiveLen;}这个方法从InputStream中读取内容,写到OutputStream中。那么发送文件方,InputStream就是,OutputStream就是Socket.getOutputStream.接受文件方,InputStream就是Socket.getInputStream,OutputStream就是FileOutputStream。就OK了。 至于存到数据库里嘛,Oracle里用Blob。搜索一下,也是一样的。从Blob能获取一个输出流。

⑺ Java文件上传的几种方式

1、通过Servlet类上传2、通过Struts框架实现上传ITJOB学到两种方式

⑻ 用java.awt java.swing 的哪个组件可以实现文件上传的图形化界面

用Swing吧JTextField用于显示文件的路径JButton用于提交上传操作,并在JButton的事件处理方法中处理上传任务就OK了。

⑼ JAVA WEB怎么实现大文件上传

解决这种大文件上传不太可能用web上传的方式,只有自己开发插件或是当门客户端上传,或者用现有的ftp等。1)开发一个web插件。用于上传文件。2)开发一个FTP工具,不用web上传。3)用现有的FTP工具。下面是几款不错的插件,你可以试试:1)Jquery的uploadify插件。具体使用。你可以看帮助文档。2)网上有一个Web大文件断点续传控件:http://www.cnblogs.com/xproer/archive/2012/02/17/2355440.html此控件支持100G文件的断点续传操作,提供了完善的开发文档,支持文件MD5验证,支持文件批量上传。JavaUploader免费开源的,是用applet实现的,需要签名才能在浏览器上用,支持断点。缺点是收费。3)applet也是一种方式,MUPLOAD组件就是以APPLET方式处理的。如果你不需要访问用户的硬盘文件,那你可以使用FTP上传,也支持断点。但只要你访问用户磁盘,又要支持断点,那必须要签名的。不然浏览器不知道你的身份。