下面這是servlet的內(nèi)容:
創(chuàng)新互聯(lián)建站是專(zhuān)業(yè)的二道網(wǎng)站建設(shè)公司,二道接單;提供成都做網(wǎng)站、網(wǎng)站建設(shè)、外貿(mào)營(yíng)銷(xiāo)網(wǎng)站建設(shè),網(wǎng)頁(yè)設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專(zhuān)業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行二道網(wǎng)站開(kāi)發(fā)網(wǎng)頁(yè)制作和功能擴(kuò)展;專(zhuān)業(yè)做搜索引擎喜愛(ài)的網(wǎng)站,專(zhuān)業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來(lái)合作!
package demo;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class DemoServlet extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8");
sfu.setProgressListener(new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("文件大小為:"+pContentLength+",當(dāng)前已處理:"+pBytesRead);
}
});
//判斷提交上來(lái)的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer= response.getWriter();
writer.println("Error:表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
factory.setSizeThreshold(MEMORY_THRESHOLD);
//設(shè)置臨時(shí)儲(chǔ)存目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//設(shè)置最大文件上傳值
sfu.setFileSizeMax(MAX_FILE_SIZE);
//設(shè)置最大請(qǐng)求值(包含文件和表單數(shù)據(jù))
sfu.setSizeMax(MAX_REQUEST_SIZE);
String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;
File file=new File(uploadpath);
if(!file.exists()){
file.mkdir();
}
try {
ListFileItem formItems = sfu.parseRequest(request);
if(formItems!=nullformItems.size()0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName=new File(item.getName()).getName();
String filePath=uploadpath+File.separator+fileName;
File storeFile=new File(filePath);
System.out.println(filePath);
item.write(storeFile);
request.setAttribute("message", "文件上傳成功!");
}
}
}
} catch (Exception e) {
request.setAttribute("message", "錯(cuò)誤信息:"+e.getMessage());
}
getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);
}
}
下面是jsp的內(nèi)容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里轉(zhuǎn)發(fā)的路徑改一下:
%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""
html
head
meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
titleInsert title here/title
/head
body
form action="demo.do" enctype="multipart/form-data" method="post"
input type="file" name="file1" /
%
String message = (String) request.getAttribute("message");
%
%=message%
input type="submit" value="提交"/
/form
/body
/html
這段代碼可以實(shí)現(xiàn)普通的文件上傳,有大小限制,上傳普通的圖片肯定沒(méi)問(wèn)題,別的一些小的文件也能傳
很簡(jiǎn)單。
可以手寫(xiě)IO讀寫(xiě)(有點(diǎn)麻煩)。
怕麻煩的話使用FileUpload組件 在servlet里doPost嵌入一下代碼
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();
//設(shè)置保存上傳文件的目錄
String uploadDir =getServletContext().getRealPath("/up");
System.out.println(uploadDir);
if (uploadDir == null)
{
out.println("無(wú)法訪問(wèn)存儲(chǔ)目錄!");
return;
}
//根據(jù)路徑創(chuàng)建一個(gè)文件
File fUploadDir = new File(uploadDir);
if(!fUploadDir.exists()){
if(!fUploadDir.mkdir())//如果UP目錄不存在 創(chuàng)建一個(gè) 不能創(chuàng)建輸出...
{
out.println("無(wú)法創(chuàng)建存儲(chǔ)目錄!");
return;
}
}
if (!DiskFileUpload.isMultipartContent(request))
{
out.println("只能處理multipart/form-data類(lèi)型的數(shù)據(jù)!");
return ;
}
DiskFileUpload fu = new DiskFileUpload();
//最多上傳200M數(shù)據(jù)
fu.setSizeMax(1024 * 1024 * 200);
//超過(guò)1M的字段數(shù)據(jù)采用臨時(shí)文件緩存
fu.setSizeThreshold(1024 * 1024);
//采用默認(rèn)的臨時(shí)文件存儲(chǔ)位置
//fu.setRepositoryPath(...);
//設(shè)置上傳的普通字段的名稱和文件字段的文件名所采用的字符集編碼
fu.setHeaderEncoding("gb2312");
//得到所有表單字段對(duì)象的集合
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);//解析request對(duì)象中上傳的文件
}
catch (FileUploadException e)
{
out.println("解析數(shù)據(jù)時(shí)出現(xiàn)如下問(wèn)題:");
e.printStackTrace(out);
return;
}
//處理每個(gè)表單字段
Iterator i = fileItems.iterator();
while (i.hasNext())
{
FileItem fi = (FileItem) i.next();
if (fi.isFormField()){
String content = fi.getString("GB2312");
String fieldName = fi.getFieldName();
request.setAttribute(fieldName,content);
}else{
try
{
String pathSrc = fi.getName();
if(pathSrc.trim().equals("")){
continue;
}
int start = pathSrc.lastIndexOf('\\');
String fileName = pathSrc.substring(start + 1);
File pathDest = new File(uploadDir, fileName);
fi.write(pathDest);
String fieldName = fi.getFieldName();
request.setAttribute(fieldName, fileName);
}catch (Exception e){
out.println("存儲(chǔ)文件時(shí)出現(xiàn)如下問(wèn)題:");
e.printStackTrace(out);
return;
}
finally //總是立即刪除保存表單字段內(nèi)容的臨時(shí)文件
{
fi.delete();
}
}
}
注意 JSP頁(yè)面的form要加enctype="multipart/form-data" 屬性, 提交的時(shí)候要向服務(wù)器說(shuō)明一下 此頁(yè)面包含文件。
如果 還是麻煩,干脆使用Struts 的上傳組件 他對(duì)FileUpload又做了封裝,使用起來(lái)更傻瓜化,很容易掌握。
-----------------------------
以上回答,如有不明白可以聯(lián)系我。
我有一段上傳圖片的代碼,并且可以根據(jù)實(shí)際,按月或按天等,生成存放圖片的文件夾
首先在JSP上放一個(gè)FILE的標(biāo)簽這些我都不說(shuō)了,你也一定明白,我直接把處理過(guò)程給你發(fā)過(guò)去
我把其中存到數(shù)據(jù)庫(kù)中的內(nèi)容刪除了,你改一下就能用
/**
*
* 上傳圖片
* @param servlet
* @param request
* @param response
* @return
* @throws Exception
*/
//這里我是同步上傳的,你隨意
public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {
SimpleDate()Format formatDate() = new SimpleDate()Format("yyyyMM");
Date nowtime=new Date();
String formatnowtime=formatDate.format(nowtime);
File root = new File(request.getRealPath("/")+"uploadfile/images/"+formatnowtime+"/"); //應(yīng)保證在根目錄中有此目錄的存在 如果沒(méi)有,下面則上創(chuàng)建新的文件夾
if(!root.isDirectory())
{
System.out.println("創(chuàng)建新文件夾成功"+formatnowtime);
root.mkdir();
}
int returnflag = 0;
SmartUpload mySmartUpload =new SmartUpload();
int file_size_max=1024000;
String ext="";
String url="uploadfile/images/"+formatnowtime+"/";
// 只允許上載此類(lèi)文件
try{
// 初始化
mySmartUpload.initialize(servlet.getServletConfig(),request,response);
mySmartUpload.setAllowedFilesList("jpg,gif,bmp,jpeg,png,JPG");
// 上載文件
mySmartUpload.upload();
} catch (Exception e){
response.sendRedirect()//返回頁(yè)面
}
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
if (myFile.isMissing()){ //沒(méi)有選擇圖片做提示!
returnflag = 3;
}else{
String myFileName=myFile.getFileName(); //取得上載的文件的文件名
ext= myFile.getFileExt(); //取得后綴名
if(ext.equals("jpg")||ext.equals("gif")||ext.equals("bmp")||ext.equals("jpeg")||ext.equals("png")||ext.equals("JPG")){ //jpeg,png不能上傳!)
int file_size=myFile.getSize(); //取得文件的大小
String saveurl="";
if(file_sizefile_size_max){
try{
//我上面說(shuō)到,把操作數(shù)據(jù)庫(kù)的代友刪除了,這里就應(yīng)該是判斷,你的圖片是不是已經(jīng)存在了,存在要怎么處理,不存在要怎么處了,就是你的事了 }
//更改文件名,取得當(dāng)前上傳時(shí)間的毫秒數(shù)值
Calendar calendar = Calendar.getInstance();
//String filename = String.valueOf(calendar.getTimeInMillis());
String did = contractBean.getMaxSeq("MULTIMEDIA_SEQ");
String filename = did;
String flag = "0";
String path = request.getRealPath("/")+url;
String ename = myFile.getFileExt();
//.toLowerCase()轉(zhuǎn)換大小寫(xiě)
saveurl=request.getRealPath("/")+url;
saveurl+=filename+"."+ext; //保存路徑
myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);
//將圖片信息插入到數(shù)據(jù)庫(kù)中
// ------上傳完成,開(kāi)始生成縮略圖-----
java.io.File file = new java.io.File(saveurl); //讀入剛才上傳的文件
String newurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的縮略圖保存地址
Image src = javax.imageio.ImageIO.read(file); //構(gòu)造Image對(duì)象
float tagsize=200;
int old_w=src.getWidth(null);
int old_h=src.getHeight(null);
int new_w=0;
int new_h=0;
int tempsize;
float tempdouble;
if(old_wold_h){
tempdouble=old_w/tagsize;
}else{
tempdouble=old_h/tagsize;
}
// new_w=Math.round(old_w/tempdouble);
// new_h=Math.round(old_h/tempdouble);//計(jì)算新圖長(zhǎng)寬
new_w=150;
new_h=110;//計(jì)算新圖長(zhǎng)寬
BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //繪制縮小后的圖
FileOutputStream newimage=new FileOutputStream(newurl); //輸出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag); //近JPEG編碼
newimage.close();
returnflag = 1;
}else{
returnflag = 0;
System.out.println("('上傳文件大小不能超過(guò)"+(file_size_max/1000)+"K');");
}
}else{
returnflag = 2;
}
}
response.sendRedirect();
return "11";
}
用struts也可以實(shí)現(xiàn) 多文件上傳
下面是我寫(xiě)的代碼,作為參考!
/*文件目錄*/
public static String [] fileArray={
"logo.png",
"index.swf",
"OEMInfo.txt",
"favicon.ico"};
/**
* @author Caoshun
* @see 接收并保存文件
* */
public static void receiveAndSaveAllFileByPath(ActionForm form,String rootPath1,String rootPath2){
String fileName="";
//獲取表單中的文件資源
HashtableObject, Object files = form.getMultipartRequestHandler().getFileElements();
//遍歷文件,并且循環(huán)保存
//當(dāng)前處理文件序號(hào)
int file_num=1;
for (EnumerationObject e = files.keys(); e.hasMoreElements();) {
/*根據(jù)處理的當(dāng)前文件下標(biāo),確定文件名*/
fileName=fileArray[file_num-1];
FormFile file = (FormFile) files.get((String) e.nextElement());
if (file != null file.getFileSize() 0) {
try {
//使用formfile.getInputStream()來(lái)獲取一個(gè)文件的輸入流進(jìn)行保存。
//文件名
//String fileName = file.getFileName();
//System.out.println("debug in AddEnterpriceAction.java on line 152 fileName is : "+fileName);
//文件大小
//int fileSize = file.getFileSize();
//文件流
InputStream is = file.getInputStream();
//將輸入流保存到文件
//String rootPath = this.servlet.getServletContext().getRealPath("files");
//往cn中寫(xiě)入
File rf = new File(rootPath1);
FileOutputStream fos = null;
fos = new FileOutputStream(new File(rf, fileName));
byte[] b = new byte[10240];
int real = 0;
real = is.read(b);
while (real 0) {
fos.write(b, 0, real);
real = is.read(b);
}
//往en中寫(xiě)入
File rf2 = new File(rootPath2);
InputStream is2 = file.getInputStream();
FileOutputStream fos2 = null;
fos2 = new FileOutputStream(new File(rf2, fileName));
byte[] b2 = new byte[10240];
int real2 = 0;
real2 = is2.read(b2);
while (real2 0) {
fos2.write(b2, 0, real2);
real2 = is2.read(b2);
}
//關(guān)閉文件流
fos.close();
is.close();
fos2.close();
is2.close();
} catch (RuntimeException e1) {
e1.printStackTrace();
} catch (Exception ee) {
ee.printStackTrace();
}
file.destroy();
}
file_num++;
}
}
package com;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.jspsmart.upload.*;
public class uploadfiles extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
//使用了一個(gè)第三方的組件,存放在web-inf/lib下
response.setContentType("text/html;charset=GB2312");
//由于SmartUpload的初始化方法需要pageContext,所以我們?cè)趕ervlet中得到他
//為了得到pageConext要首先得到JspFactory的實(shí)例
//通過(guò)JspFactory的實(shí)例的getPageContext方法得到pageConext的實(shí)例
JspFactory jf = null;
//得到JspFactory的實(shí)例
jf=JspFactory.getDefaultFactory();
/*
getPageContext(Servlet servlet,
ServletRequest request,
ServletResponse response,
java.lang.String errorPageURL,
boolean needsSession,
int buffer,
boolean autoflush)
*/
PageContext pageContext=jf.getPageContext(this,request,response,null,true,8192,true);
try
{
//實(shí)例化SmartUpload
SmartUpload mySmartUpload=new SmartUpload();
//初始化SmartUpload的實(shí)例,需要PageContext的實(shí)例
mySmartUpload.initialize(pageContext);
//設(shè)定最大上傳的字節(jié)數(shù),其實(shí)可以不進(jìn)行設(shè)定,表示上傳的文件沒(méi)有大小限制
//mySmartUpload.setTotalMaxFileSize(10000000);
mySmartUpload.upload();
//下面是單文件上傳
//上傳的文件以com.jspsmart.upload.File 代表,如果文件名稱重復(fù),則進(jìn)行覆蓋
com.jspsmart.upload.File file=mySmartUpload.getFiles().getFile(0);
String upLoadFileName=file.getFileName();
//調(diào)用com.jspsmart.upload.File實(shí)例的saveas的方法保存文件,此時(shí)的文件名即是
//保存到服務(wù)器上的文件名
file.saveAs("/upload/"+upLoadFileName);
Request req =
Text t = .....;
t.setUpload(upLoadFileName);
t.set.....(req);
}
catch(SmartUploadException e)
{
System.out.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
doGet(request,response);
}
}
首先,我們創(chuàng)建一個(gè)新的web工程,在工程的WebRoot目錄下新建一個(gè)upload文件夾,這樣當(dāng)我們將該工程部署到服務(wù)器上時(shí),服務(wù)器便也生成個(gè)upload文件夾,用來(lái)存放上傳的資源。
然后,在WebRoot目錄下新建一個(gè)jsp文件,主要實(shí)現(xiàn)的作用就是選擇上傳的文件,提交至servlet來(lái)進(jìn)行處理
詳細(xì)代碼如下:一個(gè)form將文件信息通過(guò)post方式傳送到指定的servlet
%@?page?language="java"?import="java.util.*"?pageEncoding="utf-8"%?
%?
String?path?=?request.getContextPath();?
String?basePath?=?
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";?%?
!DOCTYPE?HTML?PUBLIC?"-//W3C//DTD?HTML?4.01?Transitional//EN"?html?head?
base?%=basePath%"?
titleMy?JSP?'upload.jsp'?starting?page/title?meta?http-equiv="pragma"?content="no-cache"?
meta?http-equiv="cache-control"?content="no-cache"?meta?http-equiv="expires"?content="0"?
meta?http-equiv="keywords"?content="keyword1,keyword2,keyword3"?meta?http-equiv="description"?content="This?is?my?page"?!--?
link?rel="stylesheet"?type="text/css"??--?
/head?
body?
form?action="/upload/UpLoad"?method="post"?enctype="multipart/form-data"?
請(qǐng)選擇上傳的圖片或文件:input?type="file"?name="fileName"/input?type="submit"?value="上傳"/?
/form?
/body
/html
可以看到,我們將數(shù)據(jù)提交到工程下的upload/UpLoad。 之后,我們就來(lái)編寫(xiě)這個(gè)servlet——UpLoad.java
package?load;?import?java.io.File;?
import?java.io.IOException;?import?java.io.PrintWriter;?import?java.util.List;?
import?javax.servlet.ServletContext;?import?javax.servlet.ServletException;?import?javax.servlet.http.HttpServlet;?
import?javax.servlet.http.HttpServletRequest;?import?javax.servlet.http.HttpServletResponse;?import?mons.fileupload.FileItem;?
import?mons.fileupload.FileUploadException;?import?mons.fileupload.disk.DiskFileItemFactory;?import?mons.fileupload.servlet.ServletFileUpload;?public?class?UpLoad?extends?HttpServlet?{?@SuppressWarnings("unchecked")?@Override?
protected?void?service(HttpServletRequest?req,?HttpServletResponse?resp)?throws?ServletException,?IOException?{?req.setCharacterEncoding("utf-8");?
resp.setContentType("text/html;charset=utf-8");?
//為解析類(lèi)提供配置信息?
DiskFileItemFactory?factory?=?new?DiskFileItemFactory();?
//創(chuàng)建解析類(lèi)的實(shí)例?
ServletFileUpload?sfu?=?new?ServletFileUpload(factory);?
//開(kāi)始解析?
sfu.setFileSizeMax(1024*400);?
//每個(gè)表單域中數(shù)據(jù)會(huì)封裝到一個(gè)對(duì)應(yīng)的FileItem對(duì)象上?try?{?
ListFileItem?items?=?sfu.parseRequest(req);?
//區(qū)分表單域?
for?(int?i?=?0;?i??items.size();?i++)?{?FileItem?item?=?items.get(i);?
var?cpro_psid?="u2572954";?var?cpro_pswidth?=966;?var?cpro_psheight?=120;
//isFormField為true,表示這不是文件上傳表單域?if(!item.isFormField()){?
ServletContext?sctx?=?getServletContext();?
//獲得存放文件的物理路徑?
//upload下的某個(gè)文件夾?得到當(dāng)前在線的用戶?找到對(duì)應(yīng)的文件夾??
String?path?=?sctx.getRealPath("/upload");?System.out.println(path);?
//獲得文件名?
String?fileName?=?item.getName();?System.out.println(fileName);?
//該方法在某些平臺(tái)(操作系統(tǒng)),會(huì)返回路徑+文件名?
fileName?=?fileName.substring(fileName.lastIndexOf("/")+1);?File?file?=?new?File(path+"\\"+fileName);?if(!file.exists()){?item.write(file);?
//將上傳圖片的名字記錄到數(shù)據(jù)庫(kù)中??
resp.sendRedirect("/upload/l");?}?}?}?
}?catch?(Exception?e)?{?e.printStackTrace();?}??
}?
}
因?yàn)橐褜?duì) 代碼做了詳細(xì)的注釋?zhuān)韵嘈糯蠹乙材芑旧蟼鞯倪@個(gè)過(guò)程。要注意的一點(diǎn)是解析實(shí)例空間大小的設(shè)置。我們希望上傳的文件不會(huì)是無(wú)限大,因此,設(shè)置
.setFileSizeMax(1024*400);