当前位置:首页 > 代码 > 正文

jsp上传下载附件代码(java附件上传下载)

admin 发布:2022-12-19 20:35 187


今天给各位分享jsp上传下载附件代码的知识,其中也会对java附件上传下载进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

JSP做的简单的文件上传下载代码

//////////////////////用Servlvet实现文件上传,参考参考吧

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class UploadTest extends HttpServlet {

String rootPath, successMessage;

static final int MAX_SIZE = 102400;

public void init(ServletConfig config) throws ServletException

{

super.init(config);

}

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException,IOException

{

response.setContentType("text/html");

PrintWriter out = new PrintWriter (response.getOutputStream());

out.println("html");

out.println("headtitleServlet1/title/head");

out.println("bodyform ENCTYPE=\"multipart/form-data\" method=post action=''input type=file enctype=\"multipart/form-data\" name=filedata");

out.println("input type=submit/form");

out.println("/body/html");

out.close();

}

public void doPost(HttpServletRequest request,HttpServletResponse response)

{

ServletOutputStream out=null;

DataInputStream in=null;

FileOutputStream fileOut=null;

try

{

/*set content type of response and get handle to output stream in case we are unable to redirect client*/

response.setContentType("text/plain");

out = response.getOutputStream();

}

catch (IOException e)

{

//print error message to standard out

System.out.println("Error getting output stream.");

System.out.println("Error description: " + e);

return;

}

try

{

String contentType = request.getContentType();

//make sure content type is multipart/form-data

if(contentType != null contentType.indexOf("multipart/form-data") != -1)

{

//open input stream from client to capture upload file

in = new DataInputStream(request.getInputStream());

//get length of content data

int formDataLength = request.getContentLength();

//allocate a byte array to store content data

byte dataBytes[] = new byte[formDataLength];

//read file into byte array

int bytesRead = 0;

int totalBytesRead = 0;

int sizeCheck = 0;

while (totalBytesRead formDataLength)

{

//check for maximum file size violation

sizeCheck = totalBytesRead + in.available();

if (sizeCheck MAX_SIZE)

{

out.println("Sorry, file is too large to upload.");

return;

}

bytesRead = in.read(dataBytes, totalBytesRead, formDataLength);

totalBytesRead += bytesRead;

}

//create string from byte array for easy manipulation

String file = new String(dataBytes);

//since byte array is stored in string, release memory

dataBytes = null;

/*get boundary value (boundary is a unique string that

separates content data)*/

int lastIndex = contentType.lastIndexOf("=");

String boundary = contentType.substring(lastIndex+1,

contentType.length());

//get Directory web variable from request

String directory="";

if (file.indexOf("name=\"Directory\"") 0)

{

directory = file.substring(file.indexOf("name=\"Directory\""));

//remove carriage return

directory = directory.substring(directory.indexOf("\n")+1);

//remove carriage return

directory = directory.substring(directory.indexOf("\n")+1);

//get Directory

directory = directory.substring(0,directory.indexOf("\n")-1);

/*make sure user didn't select a directory higher in the directory tree*/

if (directory.indexOf("..") 0)

{

out.println("Security Error: You can't upload " +"to a directory higher in the directory tree.");

return;

}

}

//get SuccessPage web variable from request

String successPage="";

if (file.indexOf("name=\"SuccessPage\"") 0)

{

successPage = file.substring(file.indexOf("name=\"SuccessPage\""));

//remove carriage return

successPage = successPage.substring(successPage.indexOf("\n")+1);

//remove carriage return

successPage = successPage.substring(successPage.indexOf("\n")+1);

//get success page

successPage = successPage.substring(0,successPage.indexOf("\n")-1);}

//get OverWrite flag web variable from request

String overWrite;

if (file.indexOf("name=\"OverWrite\"") 0)

{

overWrite = file.substring(file.indexOf("name=\"OverWrite\""));

//remove carriage return

overWrite = overWrite.substring(

overWrite.indexOf("\n")+1);

//remove carriage return

overWrite = overWrite.substring(overWrite.indexOf("\n")+1);

overWrite = overWrite.substring(0,overWrite.indexOf("\n")-1);

}

else

{

overWrite = "false";

}

//get OverWritePage web variable from request

String overWritePage="";

if (file.indexOf("name=\"OverWritePage\"") 0)

{

overWritePage = file.substring(file.indexOf("name=\"OverWritePage\""));

//remove carriage return

overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);

//remove carriage return

overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);

//get overwrite page

overWritePage = overWritePage.substring(0,overWritePage.indexOf("\n")-1);

}

//get filename of upload file

String saveFile = file.substring(file.indexOf("filename=\"")+10);

saveFile = saveFile.substring(0,saveFile.indexOf("\n"));

saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+1,

saveFile.indexOf("\""));

/*remove boundary markers and other multipart/form-data

tags from beginning of upload file section*/

int pos; //position in upload file

//find position of upload file section of request

pos = file.indexOf("filename=\"");

//find position of content-disposition line

pos = file.indexOf("\n",pos)+1;

//find position of content-type line

pos = file.indexOf("\n",pos)+1;

//find position of blank line

pos = file.indexOf("\n",pos)+1;

/*find the location of the next boundary marker

(marking the end of the upload file data)*/

int boundaryLocation = file.indexOf(boundary,pos)-4;

//upload file lies between pos and boundaryLocation

file = file.substring(pos,boundaryLocation);

//build the full path of the upload file

String fileName = new String(rootPath + directory +

saveFile);

//create File object to check for existence of file

File checkFile = new File(fileName);

if (checkFile.exists())

{

/*file exists, if OverWrite flag is off, give

message and abort*/

if (!overWrite.toLowerCase().equals("true"))

{

if (overWritePage.equals(""))

{

/*OverWrite HTML page URL not received, respond

with generic message*/

out.println("Sorry, file already exists.");

}

else

{

//redirect client to OverWrite HTML page

response.sendRedirect(overWritePage);

}

return;

}

}

/*create File object to check for existence of

Directory*/

File fileDir = new File(rootPath + directory);

if (!fileDir.exists())

{

//Directory doesn't exist, create it

fileDir.mkdirs();

}

//instantiate file output stream

fileOut = new FileOutputStream(fileName);

//write the string to the file as a byte array

fileOut.write(file.getBytes(),0,file.length());

if (successPage.equals(""))

{

/*success HTML page URL not received, respond with

eneric success message*/

out.println(successMessage);

out.println("File written to: " + fileName);

}

else

{

//redirect client to success HTML page

response.sendRedirect(successPage);

}

}

else //request is not multipart/form-data

{

//send error message to client

out.println("Request not multipart/form-data.");

}

}

catch(Exception e)

{

try

{

//print error message to standard out

System.out.println("Error in doPost: " + e);

//send error message to client

out.println("An unexpected error has occurred.");

out.println("Error description: " + e);

}

catch (Exception f) {}

}

finally

{

try

{

fileOut.close(); //close file output stream

}

catch (Exception f) {}

try

{

in.close(); //close input stream from client

}

catch (Exception f) {}

try

{

out.close(); //close output stream to client

}

catch (Exception f) {}

}

}

}

我想用jsp语言编写的网页中实现文件上传、下载的功能,请问完整的代码怎么写,尽量是最简单的,谢谢

input type='file'

然后设置form的 enctype= "multipart/form-data "

然后后台从HttpServletRequest里面取文件出来就ok了!

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;

求一段能用的jsp上传文件的代码

%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%

%@ page language="java" import="java.io.*,com.jspsmart.upload.*"%

HTMLHEAD

meta http-equiv="Content-Type" content="text/html";charset=UFT-8

TITLESave upload  /TITLE

/HEAD  

BODY  

%

 // 将上传文件全部保存到指定目录创建文件夹使用绝对路径

String uploadPath =request.getRealPath("/")+"/images/";

java.io.File fdir = new java.io.File(uploadPath);

if(!fdir.exists()){

    fdir.mkdirs();

}

  

SmartUpload su = new SmartUpload();

su.initialize(pageContext);

// 设定上传限制

// 1.限制每个上传文件的最大长度。

//su.setMaxFileSize(5120000); //5M

// 2.限制总上传数据的长度。

//su.setTotalMaxFileSize(25600000);//5M*5

// 3.设定允许上传的文件(通过扩展名限制)。

//su.setAllowedFilesList("gif,jpg,png,bmp,GIF,JPG,PNG,BMP");

// 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,

//jsp,htm,html扩展名的文件和没有扩展名的文件。

//su.setDeniedFilesList("exe,bat,jsp,htm,html,,");

// 上传文件

su.upload();

String x = su.getRequest().getParameter("x") ;

 

out.println("table border='1' width='560'");

out.println("tr");

out.println("th文件名/th");

out.println("th文件大小/th");

out.println("/tr");

for(int i=0;isu.getFiles().getCount();i++){

    com.jspsmart.upload.File file=su.getFiles().getFile(i);

    if(file.isMissing()){

        continue;

    }

    out.println("tr");

    out.println("td"+file.getFileName()+"/td");

    out.println("td"+file.getSize()+"/td");

    out.println("/tr");

    String ext="."+file.getFileExt();

    String strtemp=uploadPath+"/"+x+ext;

    

    file.saveAs(strtemp);

}

out.println("/table");

%

/body

/html

上面是完整的代码。

jsp上传文件代码!

其实就是读流的形式。我这有个struts1的,自己研究下。可以批量上传配置文件:#路径请用双\

path=c:\\test\\

#大小为b

fileSize=5000

#文件类型用","隔开

fileType=jpg,txt主要类:// 路径常量

public static final String FILEPATH = "path";

// 文件大小

public static final String FILESIZE = "fileSize";

// 文件类型

public static final String FILETYPE = "fileType"; /**

* @param key:资源文件key值

* @return 返回对应key的value

*/

public static String getValueByKey(String key) {

String rKey = "";

CommonUtil util = new CommonUtil();

// 获取资源文件流

InputStream in = util.getClass().getResourceAsStream(

"/upload.properties"); Properties props = new Properties();

try {

// 加载资源文件

props.load(in);

// 获取资源文件对应key值

rKey = props.get(key).toString();

in.close();

} catch (IOException e) {

e.printStackTrace(); }

return rKey; // 遍历所有key值

// Set set = props.keySet();

// Iterator it = set.iterator();

// System.out.println("Begin ...");

// while(it.hasNext()){

// System.out.println((String)it.next());

// }

// System.out.println("End");

} /**

* 根据系统时间+两位数字随机数产生文件名

*

* @return 例:2010091521202315

*/

public static String getFileName() {

// 格式化日期

SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");

String fileName = s.format(new Date());

// 随机数

Random r = new Random();

int random = 0;

do {

random = r.nextInt(100);

} while (random 10);

// 连接字符串

fileName += random;

return fileName;

} /**

* 上传文件集合

*

* @param files:FormFile的集合

* @param code:数据字典模块路径id

* @param fileName:文件真实名称

* @return 上传后的文件id数组

*/

public static String[] filesUpload(List files, int code, String[] fileName)

throws IOException, Exception {

// 输出文件名

for (int i = 0; i fileName.length; i++) {

System.out.println("文件" + (i + 1) + "名字:" + fileName[i]);

}

// 获取资源文件上传路径

String path = CommonUtil.getValueByKey(CommonUtil.FILEPATH);

System.out.println("资源文件路径:" + path);

// 获取大小文件上限

long fileSize = Long.parseLong(CommonUtil

.getValueByKey(CommonUtil.FILESIZE));

System.out.println("文件上限大小:" + fileSize + "b");

// 获取文件类型

String types = CommonUtil.getValueByKey(CommonUtil.FILETYPE).toString();

System.out.println("限制文件类型:" + types);

// 数组转为集合

List fileTypes = Arrays.asList(types.split(",")); // 首先遍历文件集合判断是否合法

for (Iterator iterator = files.iterator(); iterator.hasNext();) {

// 单个文件

FormFile file = (FormFile) iterator.next();

// 文件类型

String ext = file.getFileName().substring(

file.getFileName().lastIndexOf(".") + 1,

file.getFileName().length());

// 遍历文件类型集合进行判断

if (!fileTypes.contains(ext)) {

throw new Exception("不允许上传" + ext + "类型文件");

}

if (fileSize file.getFileSize()) {

throw new Exception("上传的文件过大");

}

}

for (Iterator iterator = files.iterator(); iterator.hasNext();) {

// 单个文件

FormFile file = (FormFile) iterator.next(); /*

* 。。。。。。。。。。。。。。。实际上传路径

*/

// 根据实际上传路径新建文件夹

new File(path).mkdirs();

// 文件输出路径

String savePath = path + getFileName() + ".jpg";

System.out.println("文件输出路径" + savePath);

if (file.getFileSize() 10) {

// 输入流

InputStream input = file.getInputStream();

byte[] b = new byte[1024];

// 输出流

FileOutputStream fileoutput = new FileOutputStream(savePath);

// 开始输出

while (input.read(b) != -1) {

fileoutput.write(b);

}

fileoutput.close();

input.close();

// 文件上传结束

}

}

/*

* 。。。。。。。。。。。。。。获取上传后的文件名

*/

return null;

}

关于jsp上传下载附件代码和java附件上传下载的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

版权说明:如非注明,本站文章均为 AH站长 原创,转载请注明出处和附带本文链接;

本文地址:http://ahzz.com.cn/post/23097.html


取消回复欢迎 发表评论:

分享到

温馨提示

下载成功了么?或者链接失效了?

联系我们反馈

立即下载