『壹』 java在jsp中 如何上傳圖片 在上傳時可以取到圖片大小並修改
用第三方工具去取 common-upload,具體取到圖片的方法參考代碼如下:
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
upload.setHeaderEncoding("utf-8");
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
System.out.println("fileName=" + fileItem.getFieldName());
//獲取文件流
InputStream in = fileItem.getInputStream();
ServletContext context = getServletConfig().getServletContext();
String path = context.getRealPath("image");
System.out.println(path);
OutputStream out = new FileOutputStream(new File(path + "\\" + fileItem.getName()));
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
System.out.println("寫入完畢");
}
} catch (FileUploadException e) {
e.printStackTrace();
}
『貳』 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";
}
}
『叄』 鍏鍙歌佹眰鍋氫竴涓猨ava鍜宩sp鎬庝箞瀹炵幇ftp涓婁紶鐨勫姛鑳芥ā鍧楋紝鎴戞病鏈夊仛榪囷紝璋佹湁璁插緱緇嗕竴鐐圭殑鏂囩珷鎴栫綉絝欍
form琛ㄥ崟鎻愪氦鏂囦歡錛屽緩璁鐢╯martupload涓婁紶錛屾殏瀛樺湪web鏈嶅姟鍣ㄧ洰褰曚笅錛岀劧鍚庣◢寰涓涓嬩笅闈㈢殑浠g爜錛宖tp涓婁紶鍚庯紝鍒犻櫎鏆傚瓨鏂囦歡錛宱k
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
/**
* Ftp 鏈嶅姟綾伙紝瀵笰pache鐨刢ommons.net.ftp榪涜屼簡鍖呰<br>
* 渚濊禆搴撴枃浠訛細commons-net-1.4.1.jar
*
* @version 1.0 2008-02-18
* @author huchao@jbsoft
*/
public class FtpService {
public FtpService(String serverAddr, String lsenport, String userName,
String pswd) {
this.ftpServerAddress = serverAddr;
this.port = Integer.parseInt(lsenport);
this.user = userName;
this.password = pswd;
}
/**
* FTP 鏈嶅姟鍣ㄥ湴鍧
*/
private String ftpServerAddress = null;
/**
* FTP 鏈嶅姟絝鍙
*/
private int port = 21;
/**
* FTP 鐢ㄦ埛鍚
*/
private String user = null;
/**
* FTP 瀵嗙爜
*/
private String password = null;
/**
* FTP 鏁版嵁浼犺緭瓚呮椂鏃墮棿
*/
private int timeout = 0;
/**
* 寮傚父錛氱櫥褰曞け璐
*/
private final I2HFException EXCEPTION_LOGIN = new I2HFException("COR101",
"FTP鏈嶅姟鍣ㄧ櫥褰曞け璐");
/**
* 寮傚父錛氭枃浠朵紶杈撳け璐
*/
private final I2HFException EXCEPTION_FILE_TRANSFER = new I2HFException(
"COR010", "FTP鏂囦歡浼犺緭澶辮觸");
/**
* 寮傚父錛欼O寮傚父
*/
private final I2HFException EXCEPTION_GENERAL = new I2HFException("COR010",
"FTP IO 寮傚父");
private static final Logger logger = Logger.getLogger(FtpService.class);
/**
* 鍒濆嬪寲FTP榪炴帴錛屽苟榪涜岀敤鎴風櫥褰
*
* @return FTPClient
* @throws I2HFException
*/
public FTPClient initConnection() throws I2HFException {
FTPClient ftp = new FTPClient();
try {
// 榪炴帴鍒癋TP
ftp.connect(ftpServerAddress, port);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new I2HFException("COR010", "FTP鏈嶅姟鍣ㄨ繛鎺ュけ璐");
}
// 鐧誨綍
if (!ftp.login(user, password)) {
throw EXCEPTION_LOGIN;
}
// 浼犺緭妯″紡浣跨敤passive
ftp.enterLocalPassiveMode();
// 璁劇疆鏁版嵁浼犺緭瓚呮椂鏃墮棿
ftp.setDataTimeout(timeout);
logger.info("FTP鏈嶅姟鍣╗" + ftpServerAddress + " : " + port + "]鐧誨綍鎴愬姛");
} catch (I2HFException te) {
logger.info(te.errorMessage, te);
throw te;
} catch (IOException ioe) {
logger.info(ioe.getMessage(), ioe);
throw EXCEPTION_LOGIN;
}
return ftp;
}
/**
* 璁劇疆浼犺緭鏂瑰紡
*
* @param ftp
* @param binaryFile
* true:浜岃繘鍒/false:ASCII
* @throws I2HFException
*/
public void setTransferMode(FTPClient ftp, boolean binaryFile)
throws I2HFException {
try {
if (binaryFile) {
ftp.setFileType(FTP.BINARY_FILE_TYPE);
logger.info("FTP鏂囦歡浼犺緭鏂瑰紡涓猴細浜岃繘鍒");
} else {
ftp.setFileType(FTP.ASCII_FILE_TYPE);
logger.info("FTP鏂囦歡浼犺緭鏂瑰紡涓猴細ASCII");
}
} catch (IOException ex) {
logger.info(ex.getMessage(), ex);
throw EXCEPTION_GENERAL;
}
}
/**
* 鍦ㄥ綋鍓嶅伐浣滅洰褰曚笅寤虹珛澶氱駭鐩褰曠粨鏋
*
* @param ftp
* @param dir
* @throws I2HFException
*/
public void makeMultiDirectory(FTPClient ftp, String dir)
throws I2HFException {
try {
StringBuffer fullDirectory = new StringBuffer();
StringTokenizer toke = new StringTokenizer(dir, "/");
while (toke.hasMoreElements()) {
String currentDirectory = (String) toke.nextElement();
fullDirectory.append(currentDirectory);
ftp.makeDirectory(fullDirectory.toString());
if (toke.hasMoreElements()) {
fullDirectory.append('/');
}
}
} catch (IOException ex) {
logger.info(ex.getMessage(), ex);
throw EXCEPTION_GENERAL;
}
}
/**
* 鏇存敼鏈嶅姟鍣ㄥ綋鍓嶈礬寰
*
* @param ftp
* @param dir
* @throws I2HFException
*/
public void changeWorkingDirectory(FTPClient ftp, String dir)
throws I2HFException {
try {
if (!ftp.changeWorkingDirectory(dir)) {
throw new I2HFException("COR010", "鐩褰昜 " + dir + "]榪涘叆澶辮觸");
}
} catch (I2HFException tfe) {
logger.info(tfe.errorMessage, tfe);
throw tfe;
} catch (IOException ioe) {
logger.info(ioe.getMessage(), ioe);
throw EXCEPTION_GENERAL;
}
}
/**
* 涓婁紶鏂囦歡鍒癋TP鏈嶅姟鍣
*
* @param ftp
* @param localFilePathName
* @param remoteFilePathName
* @throws I2HFException
*/
public void uploadFile(FTPClient ftp, String localFilePathName,
String remoteFilePathName) throws I2HFException {
InputStream input = null;
try {
input = new FileInputStream(localFilePathName);
boolean result = ftp.storeFile(remoteFilePathName, input);
if (!result) {
// 鏂囦歡涓婁紶澶辮觸
throw EXCEPTION_FILE_TRANSFER;
}
logger.info("鏂囦歡鎴愬姛涓婁紶鍒癋TP鏈嶅姟鍣");
} catch (I2HFException tfe) {
logger.info(tfe.getMessage(), tfe);
throw tfe;
} catch (IOException ioe) {
logger.info(ioe.getMessage(), ioe);
throw EXCEPTION_FILE_TRANSFER;
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
logger.info("FTP瀵硅薄鍏抽棴寮傚父", ex);
}
}
}
/**
* 涓嬭澆鏂囦歡鍒版湰鍦
*
* @param ftp
* @param remoteFilePathName
* @param localFilePathName
* @throws I2HFException
*/
public void downloadFile(FTPClient ftp, String remoteFilePathName,
String localFilePathName) throws I2HFException {
boolean downloadResult = false;
OutputStream output = null;
try {
output = new FileOutputStream(localFilePathName);
downloadResult = ftp.retrieveFile(remoteFilePathName, output);
if (!downloadResult) {
// 濡傛灉鏄鏂囦歡涓嶅瓨鍦ㄥ皢寮傚父鎶涘嚭
throw new I2HFException("COR011", "鏂囦歡涓嶅瓨鍦");
}
logger.info("鏂囦歡鎴愬姛浠嶧TP鏈嶅姟鍣ㄤ笅杞");
} catch (I2HFException tfe) {
logger.error(tfe.getMessage(), tfe);
throw tfe;
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
throw EXCEPTION_FILE_TRANSFER;
} finally {
try {
if (output != null) {
output.close();
}
if (!downloadResult) {
new File(localFilePathName).delete();
}
} catch (IOException ex) {
logger.error("FTP瀵硅薄鍏抽棴寮傚父", ex);
}
}
}
/**
* Method setFtpServerAddress.
*
* @param ftpServerAddress
* String
*/
public void setFtpServerAddress(String ftpServerAddress) {
this.ftpServerAddress = ftpServerAddress;
}
/**
* Method setUser.
*
* @param user
* String
*/
public void setUser(String user) {
this.user = user;
}
/**
* Method setPassword.
*
* @param password
* String
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Method setTimeout.
*
* @param timeout
* String
*/
public void setTimeout(String timeout) {
try {
this.timeout = Integer.parseInt(timeout);
} catch (NumberFormatException ex) {
// 榛樿よ秴鏃舵椂闂500姣縐
this.timeout = 500;
}
}
/**
* Method setPort.
*
* @param port
* String
*/
public void setPort(String port) {
try {
this.port = Integer.parseInt(port);
} catch (NumberFormatException ex) {
// 榛樿ょ鍙21
this.port = 21;
}
}
}
=====================================
jsp涓婁紶閮ㄥ垎
===================================
<form method="post" name="uploadform" id="uploadform" action="upload" ENCTYPE="multipart/form-data">
<input type="hidden" name="service" value="com.jbsoft.i2hf.corpor.services.CstBatchBizServices.exclUpload"/>
<table cellspacing="0" cellpadding="0">
<tr>
<td width="20%" align="right">涓婁紶鏈鍦版枃浠訛細</td>
<td width="80%"><input class="" style="width:300px" type="file" width="300px" name="exclname" id="exclname"/></td>
</tr>
</table>
</form>
============================================
涓婁紶鐨剆ervlet鐢ㄧ殑鏄痵martupload
錛岄儴鍒嗕唬鐮佸彲浠ュ弬鑰冧竴涓嬶細
==========================================
SmartUpload su = new SmartUpload();
su.setCharset("UTF-8");
su.initialize(getServletConfig(), request, response);
su.setMaxFileSize(10240000);
su.setTotalMaxFileSize(102400000);
su.setAllowedFilesList("xls");
su.upload();
===========================================
浠g爜閲岄潰鏈変竴浜涘㈡埛鐨勪俊鎮錛屼笉鑳藉叏閮ㄧ粰浣犲搱
『肆』 ajax怎麼提交帶文件上傳表單
上傳的文件是沒有辦法和表單內容一起非同步的,可考慮使用jquery的ajaxfileupload,或是其他的插件,非同步上傳文件後,然後再對表單進行操作。
『伍』 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;
『陸』 java編程:怎麼用JSP(javabean)上傳一張圖片到伺服器的指定文件夾呢
網路,想飛社區,在資訊里,找 WEB前端 分類,有一篇文章:AJAX JAVA 上傳文件,可以參考,抱歉,貼不了地址。。。我只能這樣說了