當前位置:首頁 » 文件管理 » 圖片上傳java代碼

圖片上傳java代碼

發布時間: 2022-11-18 01:39:16

java怎樣上傳圖片(寫個例子謝謝);

用struts2框架。。。馬上OK。。。
在響應的ACTION中,只需要定義一個File的變數即可

❷ 用java怎麼上傳圖片到項目指定的文件夾

你的意思是拷貝嗎,還是上傳到伺服器什麼的
import java.io.*;
/**
* 復制文件夾或文件夾
*/
public class CopyDirectory {
// 源文件夾
static String url1 = "f:/photos";
// 目標文件夾
static String url2 = "d:/tempPhotos";
public static void main(String args[]) throws IOException {
// 創建目標文件夾
(new File(url2)).mkdirs();
// 獲取源文件夾當前下的文件或目錄
File[] file = (new File(url1)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 復制文件
File(file[i],new File(url2+file[i].getName()));
}
if (file[i].isDirectory()) {
// 復制目錄
String sourceDir=url1+File.separator+file[i].getName();
String targetDir=url2+File.separator+file[i].getName();
Directiory(sourceDir, targetDir);
}
}
}
// 復制文件
public static void File(File sourceFile,File targetFile)
throws IOException{
// 新建文件輸入流並對它進行緩沖
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff=new BufferedInputStream(input);

// 新建文件輸出流並對它進行緩沖
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff=new BufferedOutputStream(output);

// 緩沖數組
byte[] b = new byte[1024 * 5];
int len;
while ((len =inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此緩沖的輸出流
outBuff.flush();

//關閉流
inBuff.close();
outBuff.close();
output.close();
input.close();
}
// 復制文件夾
public static void Directiory(String sourceDir, String targetDir)
throws IOException {
// 新建目標目錄
(new File(targetDir)).mkdirs();
// 獲取源文件夾當前下的文件或目錄
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile=file[i];
// 目標文件
File targetFile=new
File(new File(targetDir).getAbsolutePath()
+File.separator+file[i].getName());
File(sourceFile,targetFile);
}
if (file[i].isDirectory()) {
// 准備復制的源文件夾
String dir1=sourceDir + "/" + file[i].getName();
// 准備復制的目標文件夾
String dir2=targetDir + "/"+ file[i].getName();
Directiory(dir1, dir2);
}
}
}
}

❸ 怎麼用Java實現圖片上傳

下面這是servlet的內容:
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+",當前已處理:"+pBytesRead);

}
});
//判斷提交上來的數據是否是上傳表單的數據
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer= response.getWriter();
writer.println("Error:表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
factory.setSizeThreshold(MEMORY_THRESHOLD);
//設置臨時儲存目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//設置最大文件上傳值
sfu.setFileSizeMax(MAX_FILE_SIZE);
//設置最大請求值(包含文件和表單數據)
sfu.setSizeMax(MAX_REQUEST_SIZE);
String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;
File file=new File(uploadpath);
if(!file.exists()){
file.mkdir();
}

try {
List<FileItem> formItems = sfu.parseRequest(request);
if(formItems!=null&&formItems.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", "錯誤信息:"+e.getMessage());
}
getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);
}

}

下面是jsp的內容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里轉發的路徑改一下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert 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>
這段代碼可以實現普通的文件上傳,有大小限制,上傳普通的圖片肯定沒問題,別的一些小的文件也能傳

❹ java上傳圖片

/**
*
*/
package net.hlj.chOA.action;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.hlj.chOA..DangAnDao;
import net.hlj.chOA..LogDao;
import net.hlj.chOA..ZiYuanDao;
import net.hlj.chOA.model.DangAn;
import net.hlj.chOA.model.User;
import net.hlj.chOA.model.ZiYuan;
import net.hlj.chOA.util.GetId;

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 org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

/**
* @author lcy
*
*/
public class ZiYuanAction extends DispatchAction {

public ActionForward addZiYuan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String title = "";
String fileupload="";
SimpleDateFormat fmt = new SimpleDateFormat("yyMMddhhssmmSSS");
Date now = new Date();
String date = fmt.format(now);
String filePath = request.getSession().getServletContext().getRealPath(
"/");
String uploadPath = filePath + "upload\\uploadZiYuan\\";
String tempPath = filePath + "upload\\uploadZiYuan\\" + "uploadTemp";
String suffix = null;
if (!new File(uploadPath).isDirectory()) {
new File(uploadPath).mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4194304);// 設置初始化內存,如果上傳的文件超過該大小,將不保存到內存,而且硬碟中(單位:byte)
File fileTemp = new File(tempPath);// 建立臨時目錄
fileTemp.mkdir();
factory.setRepository(fileTemp);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4194304);// 設置客戶端最大上傳,-1為無限大(單位:byte)
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> i = items.iterator();
String[] rightType = {".gif", ".jpeg", ".doc", ".xls",
".pdf", ".txt", ".rar" };
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) {
try {
if (fi.getFieldName().equals("title")) {
title = fi.getString("UTF-8");
}
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
} else {
String fileName = fi.getName();
int l = fileName.length();
if (!fileName.equals("")) {
int pos = fileName.lastIndexOf(".");
// suffix = fileName.substring(l - 4, l);
suffix = fileName.substring(pos, l);

boolean result = false;
String ext = fileName.substring(fileName
.lastIndexOf("."));
for (int j = 0; j < rightType.length; j++) {
if (ext.toLowerCase().equals(rightType[j])) {
result = true;
break;
}
}
if (!result) {
request.setAttribute("error", "上傳文件類型有誤!");
return mapping.findForward("addZiyuan");
}

// if (!suffix.equalsIgnoreCase(".jpg") &&
// !suffix.equalsIgnoreCase(".gif")
// && !suffix.equalsIgnoreCase(".png") &&
// !suffix.equalsIgnoreCase(".bmp")) {
// request.setAttribute("message", "上傳文件類型有誤!");
// return mapping.findForward("danganList");
// }
if (fileName != null) {
File savedFile = new File(uploadPath, date + suffix);
try {
fi.write(savedFile);
fileupload = "upload/uploadZiYuan/" + date
+ suffix;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
}
} catch (FileUploadException e) {
log.error(e.getMessage(), e);
}
ZiYuan zy=new ZiYuan();
zy.setTitle(title);
zy.setUpload(fileupload);
ZiYuanDao zyDao=new ZiYuanDao();
try {
zyDao.addZiYuan(zy, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogDao lDao=new LogDao();
//刪除操做添加日誌 isDel 0是增加,1是刪除,2是修改,3是審批
User user1 =(User)request.getSession().getAttribute("userBean");
String ip=request.getLocalAddr();
int id=GetId.getId("ziyuan", this.servlet.getServletContext());
try {
lDao.addLogMe("ziyuan", id , ip, user1.getName(), user1.getId(), 0, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapping.findForward("ziyuanList");
}

public ActionForward deleteZiYuan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String[] ids= request.getParameterValues("id");
ZiYuanDao zyDao=new ZiYuanDao();
LogDao lDao=new LogDao();
for(int i=0;i<ids.length;i++){
try {
zyDao.deleteZiYuan(Integer.parseInt(ids[i]), this.servlet.getServletContext());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User user =(User)request.getSession().getAttribute("userBean");
String ip=request.getLocalAddr();
try {
lDao.addLogMe("tbl_users",Integer.parseInt(ids[i]), ip, user.getName(), user.getId(), 1, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return mapping.findForward("ziyuanList");
}

public ActionForward updateZiYuan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, SQLException {
String id="";
String title = "";
String fileupload="";
SimpleDateFormat fmt = new SimpleDateFormat("yyMMddhhssmmSSS");
Date now = new Date();
String date = fmt.format(now);
String filePath = request.getSession().getServletContext().getRealPath(
"/");
String uploadPath = filePath + "upload\\uploadZiYuan\\";
String tempPath = filePath + "upload\\uploadZiYuan\\" + "uploadTemp";
String suffix = null;
if (!new File(uploadPath).isDirectory()) {
new File(uploadPath).mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4194304);// 設置初始化內存,如果上傳的文件超過該大小,將不保存到內存,而且硬碟中(單位:byte)
File fileTemp = new File(tempPath);// 建立臨時目錄
fileTemp.mkdir();
factory.setRepository(fileTemp);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4194304);// 設置客戶端最大上傳,-1為無限大(單位:byte)
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> i = items.iterator();
String[] rightType = {".gif", ".jpeg", ".doc", ".xls",
".pdf", ".txt", ".rar" };
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) {
try {
if (fi.getFieldName().equals("title")) {
title = fi.getString("UTF-8");
}
if (fi.getFieldName().equals("id")) {
id = fi.getString("UTF-8");
}
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
} else {
String fileName = fi.getName();
int l = fileName.length();
if (!fileName.equals("")) {
int pos = fileName.lastIndexOf(".");
// suffix = fileName.substring(l - 4, l);
suffix = fileName.substring(pos, l);

boolean result = false;
String ext = fileName.substring(fileName
.lastIndexOf("."));
for (int j = 0; j < rightType.length; j++) {
if (ext.toLowerCase().equals(rightType[j])) {
result = true;
break;
}
}
if (!result) {
request.setAttribute("error", "上傳文件類型有誤!");
request.setAttribute("id", id);
return mapping.findForward("selectZiyuan");
}

// if (!suffix.equalsIgnoreCase(".jpg") &&
// !suffix.equalsIgnoreCase(".gif")
// && !suffix.equalsIgnoreCase(".png") &&
// !suffix.equalsIgnoreCase(".bmp")) {
// request.setAttribute("message", "上傳文件類型有誤!");
// return mapping.findForward("danganList");
// }
if (fileName != null) {
File savedFile = new File(uploadPath, date + suffix);
try {
fi.write(savedFile);
fileupload = "upload/uploadZiYuan/" + date
+ suffix;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}else{
//這里寫如果用戶沒有重寫添加附件則保持原來的附件
ZiYuanDao zyDao = new ZiYuanDao();
ZiYuan zy=(ZiYuan)zyDao.selectZiYuanById(Integer.parseInt(id), this.servlet.getServletContext()).get(0);
fileupload=zy.getUpload();
}
}
}
} catch (FileUploadException e) {
log.error(e.getMessage(), e);
}
ZiYuan zy=new ZiYuan();
zy.setId(Integer.parseInt(id));
zy.setTitle(title);
zy.setUpload(fileupload);
ZiYuanDao zyDao=new ZiYuanDao();
try {
zyDao.updateZiYuan(zy, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogDao lDao=new LogDao();
//刪除操做添加日誌 isDel 0是增加,1是刪除,2是修改,3是審批
User user1 =(User)request.getSession().getAttribute("userBean");
String ip=request.getLocalAddr();
try {
lDao.addLogMe("ziyuan", Integer.parseInt(id) , ip, user1.getName(), user1.getId(), 2, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return mapping.findForward("ziyuanList");
}

}

❺ java實現上傳圖片功能

首先需要先要在資料庫中建立一個數據表格一遍存儲和查詢,在數據表格中的項中添加數據區和存儲路徑。數據區用來存儲圖片,在存儲時需要用到轉換功能,讓圖片轉換成數據流字元然後才能導入資料庫進行存儲,並且在輸入同時在同一語句中添加存儲路徑。
希望以上思路能讓你有點啟發

❻ 解釋一下這段JAVA 關於圖片上傳的代碼

private File file;

private String fileFileName;
private String picture;
//都有getter 和 setter

InputStream is = new FileInputStream(file);
//引入一個IO流的輸入流
String root = ServletActionContext.getRequest()
.getRealPath("/bookpicture");
//通過REQUEST來得到相對地址,並在後面加上/bookpicture

File f = new File(root, this.getFileFileName());
//定義一個FILE文件,第一個參數是文件的路徑,第二個是文件的名字

picture="."+"\\"+"bookpicture"+"\\"+this.getFileFileName();
//為PICTURE字元串賦值,/地址/文件名
System.out.println
("======picture====="+picture);
//從控制台輸出Picture

OutputStream os = new FileOutputStream(f);
//第一個文件的輸出流

byte[] buffer = new byte[1024];
//定義一個bufer的字元串,長度為1024

int len = 0;
while ((len = is.read(buffer)) > 0) {
//如果從制定文件中讀取到的信息為結束就繼續循環
os.write(buffer, 0, len);
//將文件讀出的內容寫入到指定的文件中

}

❼ 求JAVA上傳圖片代碼

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
{
//使用了一個第三方的組件,存放在web-inf/lib下
response.setContentType("text/html;charset=GB2312");

//由於SmartUpload的初始化方法需要pageContext,所以我們在servlet中得到他
//為了得到pageConext要首先得到JspFactory的實例
//通過JspFactory的實例的getPageContext方法得到pageConext的實例
JspFactory jf = null;

//得到JspFactory的實例
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
{
//實例化SmartUpload
SmartUpload mySmartUpload=new SmartUpload();

//初始化SmartUpload的實例,需要PageContext的實例
mySmartUpload.initialize(pageContext);

//設定最大上傳的位元組數,其實可以不進行設定,表示上傳的文件沒有大小限制
//mySmartUpload.setTotalMaxFileSize(10000000);
mySmartUpload.upload();

//下面是單文件上傳
//上傳的文件以com.jspsmart.upload.File 代表,如果文件名稱重復,則進行覆蓋
com.jspsmart.upload.File file=mySmartUpload.getFiles().getFile(0);
String upLoadFileName=file.getFileName();

//調用com.jspsmart.upload.File實例的saveas的方法保存文件,此時的文件名即是
//保存到伺服器上的文件名
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);
}
}

❽ app怎麼上傳圖片到java後台java後台處理的具體代碼是怎麼寫的

使用一些已有的組件幫助我們實現這種上傳功能。常用的上傳組件:Apache的CommonsFileUploadJavaZoom的UploadBeanjspSmartUpload以下,以FileUpload為例講解1、在jsp端要注意enctype="multipart/form-data"然後只需要放置一個file控制項,並執行submit操作即可2、web端核心代碼如下:publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{request.setCharacterEncoding("UTF-8");DiskFileItemFactoryfactory=newDiskFileItemFactory();ServletFileUploapload=newServletFileUpload(factory);try{Listitems=upload.parseRequest(request);Iteratoritr=items.iterator();while(itr.hasNext()){FileItemitem=(FileItem)itr.next();if(item.isFormField()){System.out.println("表單參數名:"+item.getFieldName()+",表單參數值:"+item.getString("UTF-8"));}else{if(item.getName()!=null&&!item.getName().equals("")){System.out.println("上傳文件的大小:"+item.getSize());System.out.println("上傳文件的類型:"+item.getContentType());System.out.println("上傳文件的名稱:"+item.getName());FiletempFile=newFile(item.getName());Filefile=newFile(sc.getRealPath("/")+savePath,tempFile.getName());item.write(file);request.setAttribute("upload.message","上傳文件成功!");}else{request.setAttribute("upload.message","沒有選擇上傳文件!");}}}}catch(FileUploadExceptione){e.printStackTrace();}catch(Exceptione){e.printStackTrace();request.setAttribute("upload.message","上傳文件失敗!");}request.getRequestDispatcher("/uploadResult.jsp").forward(request,response);}

❾ java圖片批量上傳代碼

用struts也可以實現 多文件上傳
下面是我寫的代碼,作為參考!

/*文件目錄*/
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="";
//獲取表單中的文件資源
Hashtable<Object, Object> files = form.getMultipartRequestHandler().getFileElements();
//遍歷文件,並且循環保存
//當前處理文件序號
int file_num=1;
for (Enumeration<Object> e = files.keys(); e.hasMoreElements();) {

/*根據處理的當前文件下標,確定文件名*/
fileName=fileArray[file_num-1];

FormFile file = (FormFile) files.get((String) e.nextElement());
if (file != null && file.getFileSize() > 0) {
try {
//使用formfile.getInputStream()來獲取一個文件的輸入流進行保存。
//文件名
//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中寫入
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中寫入
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);
}

//關閉文件流
fos.close();
is.close();
fos2.close();
is2.close();
} catch (RuntimeException e1) {
e1.printStackTrace();
} catch (Exception ee) {
ee.printStackTrace();
}
file.destroy();

}
file_num++;
}
}

❿ java實現圖片上傳至伺服器並顯示,如何做希望要具體的代碼實現

很簡單。
可以手寫IO讀寫(有點麻煩)。
怕麻煩的話使用FileUpload組件 在servlet里doPost嵌入一下代碼
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();

//設置保存上傳文件的目錄
String uploadDir =getServletContext().getRealPath("/up");
System.out.println(uploadDir);
if (uploadDir == null)
{
out.println("無法訪問存儲目錄!");
return;
}
//根據路徑創建一個文件
File fUploadDir = new File(uploadDir);
if(!fUploadDir.exists()){
if(!fUploadDir.mkdir())//如果UP目錄不存在 創建一個 不能創建輸出...
{
out.println("無法創建存儲目錄!");
return;
}
}

if (!DiskFileUpload.isMultipartContent(request))
{
out.println("只能處理multipart/form-data類型的數據!");
return ;
}

DiskFileUpload fu = new DiskFileUpload();
//最多上傳200M數據
fu.setSizeMax(1024 * 1024 * 200);
//超過1M的欄位數據採用臨時文件緩存
fu.setSizeThreshold(1024 * 1024);
//採用默認的臨時文件存儲位置
//fu.setRepositoryPath(...);
//設置上傳的普通欄位的名稱和文件欄位的文件名所採用的字元集編碼
fu.setHeaderEncoding("gb2312");

//得到所有表單欄位對象的集合
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);//解析request對象中上傳的文件

}
catch (FileUploadException e)
{
out.println("解析數據時出現如下問題:");
e.printStackTrace(out);
return;
}

//處理每個表單欄位
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("存儲文件時出現如下問題:");
e.printStackTrace(out);
return;
}
finally //總是立即刪除保存表單欄位內容的臨時文件
{
fi.delete();
}

}
}
注意 JSP頁面的form要加enctype="multipart/form-data" 屬性, 提交的時候要向伺服器說明一下 此頁麵包含文件。

如果 還是麻煩,乾脆使用Struts 的上傳組件 他對FileUpload又做了封裝,使用起來更傻瓜化,很容易掌握。

-----------------------------
以上回答,如有不明白可以聯系我。

熱點內容
21款昂科威哪個配置好 發布:2024-10-06 02:20:39 瀏覽:835
拆裝空調壓縮機 發布:2024-10-06 01:59:47 瀏覽:419
dl演算法 發布:2024-10-06 01:59:44 瀏覽:845
寵物商店java 發布:2024-10-06 01:59:43 瀏覽:536
androidimageview文字 發布:2024-10-06 01:53:55 瀏覽:819
檢查電腦與伺服器的連通性和路徑 發布:2024-10-06 01:37:38 瀏覽:432
宋春麗訪問 發布:2024-10-06 01:34:23 瀏覽:677
美國往事ftp 發布:2024-10-06 01:29:03 瀏覽:772
dtu編程 發布:2024-10-06 01:23:30 瀏覽:595
照片視頻加密 發布:2024-10-05 23:58:58 瀏覽:480