『壹』 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 上传文件,可以参考,抱歉,贴不了地址。。。我只能这样说了