Java中实现⽂件上传下载的三种解决⽅案(推荐)
java⽂件上传与⽂件下载是程序开发中⽐较常见的功能,下⾯通过本⽂给⼤家介绍Java中实现⽂件上传下载的三种解决⽅案,具体详情如下所⽰;
第⼀点:Java代码实现⽂件上传
FormFile File();
String newfileName = null;
String newpathname=null;
String fileAddre="/numUp";
try {
InputStream stream = InputStream();// 把⽂件读⼊
String filePath = RealPath(fileAddre);//取系统当前路径
File file1 = new File(filePath);//添加了⾃动创建⽬录的功能
((File) file1).mkdir();
newfileName = System.currentTimeMillis()
+ FileName().substring(
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + "/"
+ newfileName);
newpathname=filePath+"/"+newfileName;
System.out.println(newpathname);
// 建⽴⼀个上传⽂件的输出流
System.out.println(filePath+"/"+FileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ad(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);// 将⽂件写⼊服务器
}
bos.close();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
第⼆点:Jsp页⾯上实现⽂件上传
package com.vogoal.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
public class JspFileUpload {
/** request对象 */
private HttpServletRequest request = null;
/** 上传⽂件的路径 */
private String uploadPath = null;
/** 每次读取得字节的⼤⼩ */
private static int BUFSIZE = 1024 * 8;
/** 存储参数的Hashtable */
private Hashtable paramHt = new Hasptable();
/
** 存储上传的⽂件的⽂件名的ArrayList */
private ArrayList updFileArr = new ArrayList();
/**
* 设定request对象。
*
* @param request
* HttpServletRequest request对象
*/
public void setRequest(HttpServletRequest request) {
}
/
**
* 设定⽂件上传路径。
*
* @param path
* ⽤户指定的⽂件的上传路径。
*/
public void setUploadPath(String path) {
this.uploadPath = path;
}
/**
* ⽂件上传处理主程序。�������B
*
* @return int 操作结果 0 ⽂件操作成功;1 request对象不存在。 2 没有设定⽂件保存路径或者⽂件保存路径不正确;3 * 没有设定正确的enctype;4 ⽂件操作异常。
*/
public int process() {
int status = 0;
// ⽂件上传前,对request对象,上传路径以及enctype进⾏check。
status = preCheck();
// 出错的时候返回错误代码。
if (status != 0)
return status;
try {
// ��;参数或者⽂件名�u��
String name = null;
// 参数的value
String value = null;
// 读取的流是否为⽂件的标志位
boolean fileFlag = false;
// 要存储的⽂件。
File tmpFile = null;
// 上传的⽂件的名字
String fName = null;
FileOutputStream baos = null;
BufferedOutputStream bos = null;
// ��;存储参数的Hashtable
paramHt = new Hashtable();
updFileArr = new ArrayList();
int rtnPos = 0;
byte[] buffs = new byte[BUFSIZE * 8];
// �;取得ContentType
String contentType = ContentType();
int index = contentType.indexOf("boundary=");
String boundary = "--" + contentType.substring(index + 9);
String endBoundary = boundary + "--";
/
/ �;从request对象中取得流。
ServletInputStream sis = InputStream();
// 读取1⾏
while ((rtnPos = adLine(buffs, 0, buffs.length)) != -1) {
String strBuff = new String(buffs, 0, rtnPos);
// 读取1⾏数据�n��
if (strBuff.startsWith(boundary)) {
if (name != null && im().length() > 0) {
if (fileFlag) {
bos.flush();
baos.close();
bos.close();
baos = null;
bos = null;
updFileArr.add(fName);
} else {
Object obj = (name);
ArrayList al = new ArrayList();
if (obj != null) {
al = (ArrayList) obj;
}
al.add(value);
System.out.println(value);
paramHt.put(name, al);
}
}
name = new String();
value = new String();
fileFlag = false;
fName = new String();
rtnPos = adLine(buffs, 0, buffs.length);
if (rtnPos != -1) {
strBuff = new String(buffs, 0, rtnPos);
if (LowerCase().startsWith(
"content-disposition: form-data; ")) {
int nIndex = LowerCase().indexOf(
"name=\"");
int nLastIndex = LowerCase().indexOf( "\"", nIndex + 6);
name = strBuff.substring(nIndex + 6, nLastIndex);
}
int fIndex = LowerCase().indexOf( "filename=\"");
if (fIndex != -1) {
fileFlag = true;
int fLastIndex = LowerCase().indexOf( "\"", fIndex + 10);
fName = strBuff.substring(fIndex + 10, fLastIndex); fName = getFileName(fName);
if (fName == null || im().length() == 0) { fileFlag = false;
continue;
}else{
fName = getFileNameByTime(fName);
}
}
}
} else if (strBuff.startsWith(endBoundary)) {
if (name != null && im().length() > 0) {
if (fileFlag) {
bos.flush();
baos.close();
bos.close();
baos = null;
bos = null;
updFileArr.add(fName);
} else {
Object obj = (name);
ArrayList al = new ArrayList();
if (obj != null) {
al = (ArrayList) obj;
}
al.add(value);
paramHt.put(name, al);
}
}
} else {
if (fileFlag) {
if (baos == null && bos == null) {
tmpFile = new File(uploadPath + fName);
baos = new FileOutputStream(tmpFile);
bos = new BufferedOutputStream(baos);
}
bos.write(buffs, 0, rtnPos);
baos.flush();
} else {
getsavefilenameSystem.out.println("test :" + value + "--" + strBuff); value = value + strBuff;
}
}
}
} catch (IOException e) {
status = 4;
}
return status;
}
private int preCheck() {
int errCode = 0;
if ( request == null )
return 1;
if ( uploadPath == null || im().length() == 0 ) return 2;
else{
File tmpF = new File(uploadPath);
if (!ists())
return 2;
}
String contentType = ContentType();
if ( contentType.indexOf("multipart/form-data") == -1 )
return 3;
return errCode;
}
public String getParameter(String name){
String value = "";
if ( name == null || im().length() == 0 )
return value;
value = ((name) == null)?"":(String)(((name)).get(0); return value;
}
public String[] getParameters(String name){
if ( name == null || im().length() == 0 )
return null;
if ( (name) == null )
return null;
ArrayList al = ((name);
String[] strArr = new String[al.size()];
for ( int i=0;i<al.size();i++ )
strArr[i] = ((i);
return strArr;
}
public int getUpdFileSize(){
return updFileArr.size();
}
public String[] getUpdFileNames(){
String[] strArr = new String[updFileArr.size()];
for ( int i=0;i<updFileArr.size();i++ )
strArr[i] = ((i);
return strArr;
}
private String getFileName(String input){
int fIndex = input.lastIndexOf("\\");
if (fIndex == -1) {
fIndex = input.lastIndexOf("/");
if (fIndex == -1) {
return input;
}
}
input = input.substring(fIndex + 1);
return input;
}
private String getFileNameByTime(String input){
int index = input.indexOf(".");
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return input.substring(0,index) + sdf.format(dt) + input.substring(index);
}
}
2.在Jsp页⾯中进⾏引⽤该Java类:
<%@page import="com.vogoal.util.JspFileUpload"%>
<%
//初始化
JspFileUpload jfu = new JspFileUpload();
//设定request对象
jfu.setRequest(request);
//设定上传的⽂件路径
jfu.setUploadPath("C:\\");
//上传处理
int rtn = jfu.process();
//取得form中其他input控件参数的值
String username = Parameter("username");
//如果对应同⼀个参数有多个input控件,返回数组
String[] usernameArr = Parameters("username");
//取得上传的⽂件的名字
String[] fileArr = UpdFileNames();
//取得上传⽂件的个数,这个⽅法有点鸡肋
int fileNumber = UpdFileSize();
//下⾯的是测试输出的代码。
// out.println("parameter:" + username);
// out.println("parameter size:" + usernameArr.length);
// out.println("fileArr size:" + fileArr.length);
/
/ if (fileArr.length > 0)
// out.println("fileArr 0:" + fileArr[0]);
%>
第三点:struts2实现⽂件的上传和下载
第⼆步:把form表的enctype设置为:“multipart/form-data“,如下:
Java代码
public class UploadAction{
private File uploadImage; //⽂件
private String uploadImageContentType;//⽂件的类型
private String uploadImageFileName;//⽂件的名称
private String bookname;//书名
private String author;//作者
private String savePath;//⽂件的保存位置
//属性的getter/setter⽅法
public String upload() throws Exception{
//实现上传代码,I/O操作完成
return "uploadSuccess";
}
}
注:⼀个表单⾥的⽂件域对应Action中三个属性,分别是⽂件,⽂件名,⽂件类型,命名是固定的,⽂件名必须表单中的⽂件域名称相同(uploadImage),⽂件名为:⽂件+FileName,⽂件类型:⽂件+ContentType。
第四步:将我们的上传Action配置到l中。
Java代码
<action name="upload" class="com.gqy.UploadAction">
<param name="savePath">/uploadFile</param>
<result>/success.jsp</result>
</action>
注:指定上传⽂件的在服务器上的保存⽬录,需要在UploadAction中为定义savePath变量并为其添加相应的setter和getter⽅法,便于Struts2将/uploadFile值赋给savePath属性,即要想在UploadAction中使⽤savePath变量必须在UploadAction定义。
⼿动配置⽂件过滤类型
<param name="allowTypes">
image/bmp,image/png,image/gif,image/jpeg
</param>
⼿动配置⽂件⼤⼩限制
<param name="maximumSize" >1048576</param>
使⽤Struts2的⽂件上传实现⽂件过滤
Struts2提供了⼀个⽂件上传的—fileUpload,通过配置该可以⽅便实现上传⽂件的过滤。
配置fileUpload时,可以为其指定两个参数:
allowedTypes:指定允许上传的⽂件类型,多个⽂件类型之间以英⽂逗号(,)隔开。
maximumSize:指定允许上传的⽂件⼤⼩,单位是字节。
提⽰:通过配置fileUpload,可以轻松的实现⽂过滤,当⽂件过滤失败后,系统⾃动转⼊input逻辑视图,因此必须为该Action配置名为input的逻辑视图,除此之外,还必须显⽰地为该Action配置defaultStack的引⽤。
使⽤Struts2的实现⽂件过滤配置如下:
<action name="uploadFileAction" class="com.actions.UploadFileAction">
<interceptor-ref name="defaultStack">
<!-- 配置允许上传的⽂件类型,多个⽤","分隔 -->
<param name="fileUpload.allowedTypes">
image/bmp,image/png,image/gif,image/jpeg,image/jpg
,image/x-png, image/pjpeg
</param>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。