本文目錄一覽:
- 1、jsp中如何編寫代碼實現圖片的上傳下載
- 2、jsp上傳圖片,最好完整代碼。100分!
- 3、JSP如何上傳圖片?
- 4、JSP如何上傳圖片
- 5、Jsp上傳圖片到指定文件夾下 求詳細代碼
- 6、通過JSP怎樣上傳圖片到服務器
jsp中如何編寫代碼實現圖片的上傳下載
圖片的上傳一般是用組件做的,一般不會用jsp去編寫,比較常見的圖片上傳組件有smartUpload,struts框架的file-common-upload等。
試着學習一下吧,很簡單好使。
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
STRONGFONT color=#ff0000uploadimage.jsp/FONT/STRONG
文件代碼如下:
uploadimage.jsp
文件代碼如下:view plaincopy 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
titleMy 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知道網() 詳細出處參考:
JSP如何上傳圖片?
如果你是純JSP寫的,可以用SmartUpload.在你的頁面form 里 form action=”doUpload.jsp” method=”POST” enctype=”multipart/form-data”
文件名:input type=”text” name=”name”/br
請選擇上傳的文件:input type=”file” name=”file1″/
input type=”submit” value=”上傳”/
/form 注意:enctype=”multipart/form-data”這個一定要這樣設置,具體什麼意思我也不是很清楚…..(呵呵) 提交到執行的頁面如下: //實例化上傳組件
SmartUpload upload = new SmartUpload();
//初始化上傳組件
upload.initialize(this.getServletConfig(), request, response);
//開始上傳
upload.upload();
//獲取上傳的文件列表對象
Files f = upload.getFiles();
//獲取文件對象
File fil = f.getFile(0);
//去掉文件後綴
String ext = fil.getFileExt();
//判斷文件類型是否是jpg格式jpg,gif,bmp,png,JPG,GIF,BMP,PNG
if (!(ext.equals(“jpg”)) !(ext.equals(“gif”)) !(ext.equals(“bmp”)) !(ext.equals(“png”)) !(ext.equals(“JPG”)) !(ext.equals(“GIF”)) !(ext.equals(“BMP”)) !(ext.equals(“PNG”))) {
out.println(“script type=’text/javascript’alert(‘文件類型錯誤’);location.replace(‘upLoadPhoto.jsp’);/script”);
return;
}
//滿足條件進行文件的上傳uploadImages在webRoot文件夾下的一個目錄
fil.saveAs(“uploadImages/” + fil.getFileName());
String filepath = “uploadImages/” + fil.getFileName(); //保存到數據庫的路徑 OK.這樣就可以了…..
JSP如何上傳圖片
請幾天寫了一個、代碼給你看看、說明下:這有兩個文件夾、都在Web容器(Tomcat)的根目錄下、一個臨時文件夾、一個保存上傳文件的文件夾、
UploadFile.java—–用於上傳的servlet
public class UploadFile 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 { response.setCharacterEncoding(“GBK”); response.setContentType(“text/html”); PrintWriter out = response.getWriter(); // 允許上傳的文件格式的列表 final String[] allowedExt = new String[] { “jpg”, “jpeg”, “gif” }; // 這裡對request進行封裝,RequestContext提供了對request多個訪問方法 RequestContext requestContext = new ServletRequestContext(request); // 判斷表單是否是Multipart類型的 if (FileUpload.isMultipartContent(requestContext)) { // 實例化一個硬盤工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設置緩存區的大小 factory.setSizeThreshold(1024 * 1024); // 設置目標臨時文件夾 String temp=this.getServletContext().getRealPath(“/”) + “FileTemp”; // 設置目標文件夾路徑 String path = this.getServletContext().getRealPath(“/”) + “File”; // 設置上傳文件夾路徑 factory.setRepository(new File(temp)); // 上傳組件 ServletFileUpload upload = new ServletFileUpload(factory); // 設置文件上傳的大小 upload.setFileSizeMax(3 * 1024 * 1024); ListFileItem fileList = null; try { // 獲取文件列表 fileList = upload.parseRequest(request); } catch (FileUploadException e) { if (e instanceof SizeLimitExceededException) { out.println(“文件尺寸超過規定大小:” + 3 * 1024 * 1024 + “位元組p/”); return; } e.printStackTrace(); } // 得到所有上傳文件 IteratorFileItem it = fileList.iterator(); while (it.hasNext()) { // 得到系統時間 long now = System.currentTimeMillis(); // 將long類型轉換為String類型 String prefix = String.valueOf(now); FileItem fileItem = (FileItem) it.next(); // 得到文件的後綴 String postfix = fileItem.getName().substring( fileItem.getName().lastIndexOf(“.”) + 1); // 拒絕接受規定文件格式之外的文件類型 int allowFlag = 0; int allowedExtCount = allowedExt.length; for (; allowFlag allowedExtCount; allowFlag++) { if (allowedExt[allowFlag].equals(postfix)) break; } if (allowFlag == allowedExtCount) { out.println(“請上傳以下類型的文件p /”); for (allowFlag = 0; allowFlag allowedExtCount; allowFlag++) out.println(“*.” + allowedExt[allowFlag] + ” “); return; } // 保存文件,其實就是把緩存里的數據寫到目標路徑下 File newFile = new File(path + “/” + prefix + “.” + postfix); // 文件列表為空 if (fileItem.getName() == null || fileItem.getName() == “”) { out.println(“請選擇上傳文件p /”); } try { if (newFile.createNewFile()) fileItem.write(newFile); } catch (Exception e) { e.printStackTrace(); } out.println(“文件上傳成功. 已保存為: ” + prefix + “.” + postfix + ” 文件大小:” + fileItem.getSize() + “位元組p /”); } } out.flush(); out.close(); }}由於篇幅太長、有些代碼已省去、至於儲存圖片名到數據、這個很簡單、、那裡已經取到文件名、插入到數據庫應該很簡單、這裡我不副累贅、再贈送兩個、一個下載、一個刪除、知道就跳過吧、
DownloadFile.java——-用於下載的servlet
public class DownloadFile extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileBiz fileBiz = new FileBiz(); request.setCharacterEncoding(“GBK”); // 獲取要下載的文件名 String fileName = request.getParameter(“filename”); // 獲取文件的絕對路徑 String fileDir = this.getServletContext().getRealPath(“/File”); /** 設置MS下載頁頭 */ response.setContentType(“application/x-msdownload”); response.setHeader(“Content-Disposition”, “attachment;” + ” fileame=” + fileName); //把方法寫在另一個類裏面了、 fileBiz.download(response.getOutputStream(), fileDir, fileName); }} //下載文件 public void download(OutputStream os, String fileDir,String fileName) { try { InputStream is = new FileInputStream(fileDir + “/” + fileName); int hasRead = 0; byte[] buffer = new byte[4096]; while ((hasRead = is.read(buffer, 0, buffer.length)) != -1) { os.write(buffer, 0, hasRead); } os.flush(); os.close(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { System.out.println(“下載中文件數據傳輸出錯”); e.printStackTrace(); } }
下載沒什麼好說的、注意傳過來的filename就行了、
DeleteFile.java——用於刪除的servletpublic class DeleteFile extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding(“GBK”); response.setContentType(“text/html”); PrintWriter out = response.getWriter(); // 獲取要刪除的文件名 String fileName = request.getParameter(“filename”); // 獲取文件的絕對路徑 String fileDir = this.getServletContext().getRealPath(“/File”); if(fileBiz.delete(fileDir,fileName)) out.println(“刪除成功”); else out.println(“刪除失敗”); }} //刪除文件 public boolean delete(String fileDir,String fileName){ return new File(fileDir+”/”+fileName).delete(); }
刪除文件更簡單、一行代碼的事情、
其實這些都是基於流的操作、還有很過方法等着我們去嘗試吧、
至於jar包的話、安裝時應該有、沒有百度一下、到處都是、還有一種方式上傳、下載、沒試過、用的是jspSmartUpload包、有時間研究研究、
代碼有點多、多點亂、但、也沒辦法了、希望你能看明白、
就這樣了、祝你好運、
Jsp上傳圖片到指定文件夾下 求詳細代碼
String time = new SimpleDateFormat(“yyyyMMddHHmmss”)
.format(Calendar.getInstance().getTime());// 得到系統時間
// 上傳技術
SmartUpload up = new SmartUpload();
// 進行初始化
up.initialize(this.getServletConfig(), request, response);
// 開始上傳
try {
up.upload(“utf-8”);//設置編碼方式。
int id = Integer.parseInt(up.getRequest().getParameter(“id”));// 商品編號
SmartFiles sf = up.getFiles();// 得到上傳的所有圖片
SmartFile file = sf.getFile(0);// 根據索引得到上傳圖片 多個圖片可以用循環:
String type = file.getFileExt();// 得到圖片後綴名
String folder = “tp/”;// 指定文件夾
String path = folder + time + “.” + type;// 路徑
System.out.println(path + “路徑”);
file.saveAs(request.getRealPath(“/”) + path);// 保存圖片
} catch (Exception e) {
e.printStackTrace();
}
//你搞個郵箱我把SmartUploadjar包 發給你吧。 //設置from提交
/*form action=”SellerServet” method=”post”
enctype=”multipart/form-data”*/ // 加上 enctype=”multipart/form-data
通過JSP怎樣上傳圖片到服務器
1.限制文件上傳類型只能是圖片
function checkFileType(name,file){
var extArray = new Array(“.doc”,”.docx”);
var allowSubmit = false;
if (!file){
return;
}
while (file.indexOf(“\\”) != -1){
file = file.slice(file.indexOf(“\\”) + 1);
}
var ext = file.slice(file.indexOf(“.”)).toLowerCase();
for (var i = 0; i extArray.length; i++) {
if (extArray[i] == ext){
allowSubmit = true;
break;
}
}
if(!allowSubmit){
alert(“只能上傳以下格式的文件:”+ (extArray.join(“”)) + “\n請重新選擇再上傳.”);
document.getElementById(name).value = “”;
}
}
其中:extArray是要求文件類型。可自行定義。
2.引入jQuery外部文件
jquery-2.1.4.min.js
3.編寫js代碼
$(function () {
$(‘#txtfilePath1’).uploadReview({
width: 350,
height: 350,
target: ‘#uploadReview1_content’
});
});
其中:txtfilePath1是input:file。width,height是預覽圖片的寬度和高度。target是顯示預覽圖片的位置。
4.編寫jsp頁面代碼
body
input type=”text” class=”yourClassName” name=”filePath1″ id=”filePath1″/
input type=”file” id=”txtfilePath1″ name=”txtfilePath1″ style=”display:none;”
input type=”button” onclick=”txtfilePath1.click()” id=”fileup1″ name=”fileup1″ class=”searchThing”value=”上傳”
/body
註: 這個是很久以前在網上看到的,就整理了下來,但是這麼久都沒用過,所以也沒調試過,你自己試一試研究研究, 再來網上很多博客里,他們寫的很詳細的,可以去看看
原創文章,作者:JTMK,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/137284.html