當前位置:首頁 » 文件管理 » jsp實現文件上傳

jsp實現文件上傳

發布時間: 2024-07-05 12:19:57

A. 用jsp、java實現上傳圖片,保存到資料庫,從資料庫中提取,顯示到頁面 這四步 我想問第一步,怎麼上傳圖片

用jspSmartUpload組件來實現,用jsp+servlet在Servlet里實現的代碼:

PrintWriter out = response.getWriter();
int count = 0;
// 實例化上傳控制項對象
SmartUpload su = new SmartUpload();
// 初始化操作
su.initialize(config, request, response);

// 設置上傳文件最大位元組數
su.setTotalMaxFileSize(100000);

//
try {
//禁止上傳指定擴展名的文件
su.setDeniedFilesList("ext,bat,jsp");
} catch (sqlException e1) {
e1.printStackTrace();
}

try {
// 上傳文件到伺服器
su.upload();

File fileup = new File(request.getRealPath("upload"));
if(!fileup.exists()){
// 創建目錄
fileup.mkdir();
}
// 處理多個文件的上傳
for(int i = 0;i < su.getFiles().getCount();i++){
com.jspsmart.upload.File file = su.getFiles().getFile(i);
if(!file.isMissing()){ // 如果文件有效
// 保存文件到指定上傳目錄
file.saveAs("/upload/new."+file.getFileExt(), su.SAVE_VIRTUAL);
count = su.save("/upload");
}
}

} catch (SmartUploadException e) {

e.printStackTrace();
}
out.println(count +"file(s) uploaded");

如果你對這個上傳組件不了解,最好是先去查查用法。。。

如果對您有幫助,請記得採納為滿意答案,謝謝!祝您生活愉快!

vaela

B. jsp+servlet實現文件上傳與下載源碼

上傳:
需要導入兩個包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
* 上傳附件
* @author new
*
*/
public class UploadAnnexServlet extends HttpServlet {

private static String path = "";

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

doPost(request, response);
}

/*
* post處理
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

path = this.getServletContext().getRealPath("/upload");

try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload up = new ServletFileUpload(factory);
List<FileItem> ls = up.parseRequest(request);

for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName = fileItem.getFieldName();
//getName()返回的是文件名字 普通域沒有文件 返回NULL
// String Name = fileItem.getName();
String Content = fileItem.getString("gbk");
request.setAttribute(FieldName, Content);
} else {

String nm = fileItem.getName().substring(
fileItem.getName().lastIndexOf("\\") + 1);
File mkr = new File(path, nm);
if (mkr.createNewFile()) {
fileItem.write(mkr);//非常方便的方法
}
request.setAttribute("result", "上傳文件成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("result", "上傳失敗,請查找原因,重新再試!");
}
request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(
request, response);
}

}

下載(i/o流)無需導包:
import java.io.IOException;
import java.net.URLEncoder;

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

/**
* 下載文件
* @author
*
*/
public class DownloadFilesServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 8594448765428224944L;

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

doPost(request, response);
}

/*
* 處理請求
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String name = request.getParameter("fileName");

System.out.print("dddddddddd:" + name);
// web絕對路徑
String path = request.getSession().getServletContext().getRealPath("/");
String savePath = path + "upload";

// 設置為下載application/x-download
response.setContentType("application/x-download");
// 即將下載的文件在伺服器上的絕對路徑
String filenamedownload = savePath + "/" + name;
// 下載文件時顯示的文件保存名稱
String filenamedisplay = name;
// 中文編碼轉換
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
try {
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(
filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
} catch (Exception e) {

}

}

}

C. jsp上傳圖片,最好完整代碼。100分!

upfile.jsp 文件代碼如下:

<form method="post" action="uploadimage.jsp" name="form1" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submIT" name="sub" value="upload">
</form>
<form method="post" action="uploadimage.jsp" name="form1" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="sub" value="upload">
</form>
<STRONG><FONT color=#ff0000>uploadimage.jsp</FONT></STRONG>
文件代碼如下:
uploadimage.jsp
文件代碼如下:view plain to clipboardprint?
<PRE class=java name="code"><%@ page language="java" pageEncoding="gb2312"%>
<%@ page import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*"%>
<%@ page import="mainClass.*" %>
<html>
<head>
<title>My JSP 'uploadimage.jsp' starting page</title>
</head>
<body>
<%
SmartUpload sma=new SmartUpload();
long file_max_size=4000000;
String filename1="",ext="",testvar="";
String url="uploadfiles/";
sma.initialize(pageContext);
try
{
sma.setAllowedFilesList("jpg,gif");
sma.upload();
}catch(Exception e){
%>
<script language="jscript">
alert("只允許上傳jpg,gif圖片")
window.location.href="upfile.jsp"
</script>
<%
}
try{
com.jspsmart.upload.File myf=sma.getFiles().getFile(0);
if(myf.isMissing()){
%>
<script language="jscript">
alert("請選擇要上傳的文件!")
window.location.href="upfile.jsp"
</script>
<%
}else{
ext=myf.getFileExt();
int file_size=myf.getSize();
String saveurl="";
if(file_size < file_max_size){
Calendar cal=Calendar.getInstance();
String filename=String.valueOf(cal.getTimeInMillis());
saveurl=request.getRealPath("/")+url;
saveurl+=filename+"."+ext;
myf.saveAs(saveurl,sma.SAVE_PHYSICAL);
myclass mc=new myclass(request.getRealPath("data/data.mdb"));
mc.executeInsert("insert into [path] values('uploadfiles/"+filename+"."+ext+"')");
out.println("圖片上傳成功!");
response.sendRedirect("showimg.jsp");
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
</PRE>

本文來自: IT知道網(http://www.itwis.com) 詳細出處參考:http://www.itwis.com/html/java/jsp/20080916/2409.html

D. jsp 文件上傳和下載

1.jsp頁面
<s:form action="fileAction" namespace="/file" method="POST" enctype="multipart/form-data">
<!-- name為後台對應的參數名稱 -->
<s:file name="files" label="file1"></s:file>
<s:file name="files" label="file2"></s:file>
<s:file name="files" label="file3"></s:file>
<s:submit value="提交" id="submitBut"></s:submit>
</s:form>
2.Action
//單個文件上傳可以用 File files,String filesFileName,String filesContentType
//名稱要與jsp中的name相同(三個變數都要生成get,set)
private File[] files;
// 要以File[]變數名開頭
private String[] filesFileName;
// 要以File[]變數名開頭
private String[] filesContentType;

private ServletContext servletContext;

//Action調用的上傳文件方法
public String execute() {
ServletContext servletContext = ServletActionContext.getServletContext();
String dataDir = servletContext.getRealPath("/file/upload");
System.out.println(dataDir);
for (int i = 0; i < files.length; i++) {
File saveFile = new File(dataDir, filesFileName[i]);
files[i].renameTo(saveFile);
}
return "success";
}
3.配置上傳文件臨時文件夾(在struts.xml中配置)
<constant name="struts.multipart.saveDir" value="c:/temp"/>
文件下載
1.下載的url(到Action)
<a href="${pageContext.request.contextPath}/file/fileAction!down.action">下載</a>
2.struts.xml配置
<package name="file" namespace="/file" extends="struts-default">
<action name="fileAction" class="com.struts2.file.FileAction">
<!-- 下載文件配置 -->
<!--type 為 stream 應用 StreamResult 處理-->
<result name="down" type="stream">
<!--
不管實際類型,待下載文件 ContentType 統一指定為 application/octet-stream
默認為 text/plain
-->
<param name="contentType">application/octet-stream</param>
<!--
默認就是 inputStream,它將會指示 StreamResult 通過 inputName 屬性值的 getter 方法,
比如這里就是 getInputStream() 來獲取下載文件的內容,意味著你的 Action 要有這個方法
-->
<param name="inputName">inputStream</param>
<!--
默認為 inline(在線打開),設置為 attachment 將會告訴瀏覽器下載該文件,filename 指定下載文
件保有存時的文件名,若未指定將會是以瀏覽的頁面名作為文件名,如以 download.action 作為文件名,
這里使用的是動態文件名,${fileName}, 它將通過 Action 的 getFileName() 獲得文件名
-->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!-- 輸出時緩沖區的大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
</package>
3.Action
//Action調用的下載文件方法
public String down() {
return "down";
}

//獲得下載文件的內容,可以直接讀入一個物理文件或從資料庫中獲取內容
public InputStream getInputStream() throws Exception {
String dir = servletContext.getRealPath("/file/upload");
File file = new File(dir, "icon.png");
if (file.exists()) {
//下載文件
return new FileInputStream(file);

//和 Servlet 中不一樣,這里我們不需對輸出的中文轉碼為 ISO8859-1
//將內容(Struts2 文件下載測試)直接寫入文件,下載的文件名必須是文本(txt)類型
//return new ByteArrayInputStream("Struts2 文件下載測試".getBytes());
}
return null;
}

// 對於配置中的 ${fileName}, 獲得下載保存時的文件名
public String getFileName() {
String fileName ="圖標.png";
try {
// 中文文件名也是需要轉碼為 ISO8859-1,否則亂碼
return new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return "icon.png";
}
}

E. jsp 如何實現文件上傳和下載功能

上傳:

MyjspForm mf = (MyjspForm) form;// TODO Auto-generated method stub

FormFile fname=mf.getFname();

byte [] fn = fname.getFileData();

OutputStream out = new FileOutputStream("D:\"+fname.getFileName());

Date date = new Date();

String title = fname.getFileName();

String url = "d:\"+fname.getFileName();

Upload ul = new Upload();

ul.setDate(date);

ul.setTitle(title);

ul.setUrl(url);

UploadDAO uld = new UploadDAO();

uld.save(ul);

out.write(fn);

out.close();

下載:

DownloadForm downloadForm = (DownloadForm)form;

String fname = request.getParameter("furl");

FileInputStream fi = new FileInputStream(fname);

byte[] bt = new byte[fi.available()];

fi.read(bt);

//設置文件是下載還是打開以及打開的方式msdownload表示下載;設置字湖集,//主要是解決文件中的中文信息

response.setContentType("application/msdownload;charset=gbk");

//文件下載後的默認保存名及打開方式

String contentDisposition = "attachment; filename=" + "java.txt";

response.setHeader("Content-Disposition",contentDisposition);

//設置下載長度

response.setContentLength(bt.length);

ServletOutputStream sos = response.getOutputStream();

sos.write(bt);

return null;

F. java編程:怎麼用JSP(javabean)上傳一張圖片到伺服器的指定文件夾呢

先導smartupload jar包!在寫form表單<input tyle="file" enctype="multipart/form-data" method="post">enctype和method別寫錯了!
寫一個簡單的吧!
<%page import="com.jspsmart.upload.*"%>
<%
SmartUpload su=new SmartUpload ();//初始化SmartUpload對象
try{ //捕獲他可能出現的異常
su.upload();//執行上傳
}catch(Exception ex){
ex.printStackTrace;
}
File file=su.getFile().getFile(0); //(得到單個的上傳文件的信息)這里得到的File對象是你到的jar包里的com.jspsmart.upload.File類型 別寫成IO 裡面的File了
String filepath="upload\\"; //在這之前要在你所建項目的目錄下單建一個upload文件夾
filepath+=file.getFileName();
file.saveAs(filepath,SmartUpload.SAVE-VIRTUAL);
不知道是否建了與它相對應的資料庫表啊?
不懂得再玩吧!

%>

熱點內容
訓練解壓球 發布:2024-07-08 07:53:05 瀏覽:822
vbnet存儲過程返回值 發布:2024-07-08 07:52:23 瀏覽:600
玩永劫無間要什麼配置的筆記本 發布:2024-07-08 07:39:07 瀏覽:968
超解壓筆 發布:2024-07-08 07:25:57 瀏覽:487
ffmpeg添加字幕編譯 發布:2024-07-08 07:23:46 瀏覽:145
java方法中定義方法 發布:2024-07-08 06:59:30 瀏覽:838
安卓手機門卡怎麼設置 發布:2024-07-08 06:49:05 瀏覽:994
安卓手機怎麼恢復微信刪除的聊天記錄 發布:2024-07-08 06:47:46 瀏覽:473
android菜單樣式 發布:2024-07-08 06:09:26 瀏覽:225
mui本地存儲 發布:2024-07-08 06:08:51 瀏覽:102