java jsp+servlet文件上传下载、本地及网络资源的下载

1.本地资源复制及网络资源的下载

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * 本地资源的复制和网络资源的下载Demo
 * @author
 *
 */
public class FileDemo {
public static void main(String[] args) {
String str="http://developer.baidu.com/map/jsdemo/img/logo.png";
//copyFile("F:/testFile/1.txt","F:/afterCopyFile/1.txt");
//copyFile("F:/testFile/2.jpg","F:/afterCopyFile/2.jpg");
getInternetReaources(str,"F:/netReaource/2.png");
}
/**
* 复制本地文件
* @param oldFile
* @param newFile
*/
public static void copyFile(String oldFile,String newFile){
//D:/images/a.jpg
//1 判断保存的文件所在文件夹是否存在
if(newFile!=null && !newFile.equals("") && oldFile!=null && !oldFile.equals("")){
String[] newFiles=newFile.split("/");
String saveFile="";//文件夹
String afterCopyFileName=newFiles[newFiles.length-1];//文件名称
for(int i=0;i<newFiles.length-1;i++){
saveFile+=newFiles[i]+"/";
}
System.out.println("存的文件夹=="+saveFile);
System.out.println("存的文件名=="+afterCopyFileName);
File save=new File(saveFile);
if(!save.exists()){
save.mkdirs();
}
String file=saveFile+afterCopyFileName;
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream(oldFile);
fos=new FileOutputStream(file);
byte[] buff=new byte[1024*1024];
int count=0;
while((count=fis.read(buff))!=-1){
fos.write(buff, 0, count);
}
//fos.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(fis!=null){
fis.close();
}
if(fos!=null){
fos.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
System.out.println("保存的文件为空");
}
}
/**
* 获取网络资源(图片等)
* @param str 链接 

    @param  savePath(包含保存文件名)
*/
public static void getInternetReaources(String str,String savePath){
try{
String[] newFiles=savePath.split("/");
String saveFile_2="";//文件夹
for(int i=0;i<newFiles.length-1;i++){
saveFile_2+=newFiles[i]+"/";
}
String afterCopyFileName=saveFile_2+newFiles[newFiles.length-1];//文件全名称
File save=new File(saveFile_2);
if(!save.exists()){
save.mkdirs();
}
URL url = new URL(str);
/*此为联系获得网络资源的固定格式用法,以便后面的in变量获得url截取网络资源的输入流*/
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
DataInputStream in = new DataInputStream(connection.getInputStream());
/*将参数savePath,即将截取的资源的存储在本地地址赋值给out输出流所指定的地址*/
DataOutputStream out = new DataOutputStream(new FileOutputStream(afterCopyFileName));
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read(buffer)) > 0) {/*将输入流以字节的形式读取并写入buffer中*/
out.write(buffer, 0, count);
}
/*后面三行为关闭输入输出流以及网络资源的固定格式*/
out.close();
in.close();
connection.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}

}

2.文件的上传及其下载,以及在jsp页面访问本地磁盘的图片    

jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传下载</title>
</head>
<body>
<form action="FileUpDown" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="userName"/>
密码:<input type="password" name="password"/>
文件上传:<input id="fileName01" type="file" name="fileName01" />
<br/>
文件上传:<input id="fileName02" type="file" name="fileName02" />
<br/>
文件上传:<input id="fileName03" type="file" name="fileName03"  />
<br/>
<input type="submit" name="" value="上传" />
<%=request.getAttribute("sign") %>
</form>
<!--
http://localhost:8080/     本地请求的地址
JqueryEasyUI               你的项目名
FileUpDown                 你的servlet类的类名
method=getLocationImage    你的处理方法
fileName=2.png             具体的参数
  -->
<image src="http://localhost:8080/JqueryEasyUI/FileUpDown?method=getLocationImage" /><!--显示本地磁盘的图片 -->
<div>
<a href="http://localhost:8080/JqueryEasyUI/FileUpDown?method=downLoadResource&fileName=2.png">点我下载图片</a>
<a href="http://localhost:8080/JqueryEasyUI/FileUpDown?method=downLoadResource&fileName=1.txt">点我下载txt</a>
<a href="http://localhost:8080/JqueryEasyUI/FileUpDown?method=downLoadResource&fileName=代码比较工具2.rar">点我下载代码比较工具2</a>


</div>
</body>
</html>

对应的servlet处理类

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class FileUpDown extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileUpDown() {
super();
}
/**
* 访问本地资源、下载  是通过get方式提交的
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method=request.getParameter("method");
if(method!=null && !"".equals(method) && method.equals("getLocationImage")){
try {
getLocationImage(request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(method!=null && !"".equals(method) && method.equals("downLoadResource")){
try {
downLoadResource(request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 普通的表单内容和上传的文件同时提交
*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* multipart/form-data上传回来的数据是二进制数据不能直接获取到
* String userName=request.getParameter("userName");
* 通过这个方式new String(value.getBytes("ISO-8859-1"),"UTF-8");
* */
request.setCharacterEncoding("utf-8"); 
response.setCharacterEncoding("utf-8"); 
response.setContentType("text/html;charset=utf-8"); 
//1.判断文件上传的是否没有子文件 
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart) {
// 2得到存放文件的真实路径
//String realpath = request.getSession().getServletContext().getRealPath("/files");
String myPath="E:/files";
File dir = new File(myPath);
if(!dir.exists()) {
dir.mkdirs(); 
}
//设置上传文件的临时存放路径
String tempDir="E:/tempFiles";
File tempFile=new File(tempDir);
if(!tempFile.exists()){
tempFile.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
//指定在java虚拟机内存中缓存数据大小,单位为byte,这里设为1Mb 
factory.setSizeThreshold(1 * 1024 * 1024);  
//设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 
factory.setRepository(tempFile);  
ServletFileUpload upload = new ServletFileUpload(factory);
// 指定单个上传文件的最大尺寸,单位:字节,这里设为5Mb 
//upload.setFileSizeMax(5 * 1024 * 1024); 
//指定一次上传多个文件的总尺寸,单位:字节,这里设为10Mb 
//upload.setSizeMax(10 * 1024 * 1024); 
//设置编码
upload.setHeaderEncoding("utf-8");
List<FileItem> items;
try {
//解析上传过来的文件parseRequest()
items = upload.parseRequest(request);
if(items!=null && !items.equals("") && items.size()>0){
long totalSize=0;
for(int i=0;i<items.size();i++){
if(items.get(i).getSize()>5 * 1024 * 1024){
System.out.println("singleSize=="+items.get(i).getSize());
request.setAttribute("sign", "单个文件上传限制为5M");
request.getRequestDispatcher("fileUp.jsp").forward(request, response);
return;
}else{
totalSize+=items.get(i).getSize();
}
}
if(totalSize>10 * 1024 * 1024){
System.out.println("totalSize=="+totalSize);
request.setAttribute("sign", "文件上传的总和不大于10M");
request.getRequestDispatcher("fileUp.jsp").forward(request, response);
return;
}
for(FileItem item : items) {
//getName() 返回null表示没有在表单中的file标签设置任何内容    或者""表示设置了name的值但是没有上传文件
String flag=item.getName();
if(flag!=null && !flag.equals("")){
// 获得上传文件的文件类型
String fileType = flag.substring(item.getName().lastIndexOf("."));
// 获得上传文件的文件名称
String fileName = flag.substring(0,item.getName().lastIndexOf("."));
//创建新的fileName 
fileName = fileName+System.currentTimeMillis()+fileType;
/*
* 限制上传的文件类型
String fileType = flag.substring(item.getName().lastIndexOf(".")).toLowerCase();
if(fileType.equals("jpg")){

}
*/
try{
File finallyFile=new File(myPath+"/"+fileName);
item.write(finallyFile);
request.setAttribute("sign", "上传成功");
request.getRequestDispatcher("fileUp.jsp").forward(request, response);
return ;
}catch(Exception e){
e.printStackTrace();
}finally{
item.delete();//删除存在临时 文件夹里面的文件
}
}else{
//isFormField判断是不是普通的表单字段如果是返回true 
if(item.isFormField()) {
//不是文件类型的表单数据 按照表单的顺序来提交的

//第一个是userName  第二个password  
String value=item.getString();
String name=item.getFieldName();
/*
multipart/form-data上传回来的数据是二进制数据不能直接获取到
String userName=request.getParameter("userName");
 通过这个方式new String(value.getBytes("ISO-8859-1"),"UTF-8");
 */
value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(name+"==" + value);
}
}
}
}else{//没有上传文件时可以用来返回前台提示
System.out.println("没有文件上传");
request.setAttribute("sign", "没有文件上传");
request.getRequestDispatcher("fileUp.jsp").forward(request, response);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("该文件不能上传");
}
}

//把本地图片展示在页面(F:/netReaource/2.png)
public void getLocationImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
try{
//1.本地图片
//String path=request.getParameter("path");  前台传递需要显示的图片的路径
String imagePath="F:/netReaource/2.png";
FileInputStream fis=new FileInputStream(imagePath);
OutputStream fos=response.getOutputStream();
int count=0;
byte[] buff=new byte[1024*1024];
while((count=fis.read(buff))!=-1){
fos.write(buff, 0,count);
}
fis.close();
fos.close();
}catch(Exception e){
e.printStackTrace();
}

}

//下载
public void downLoadResource(HttpServletRequest request, HttpServletResponse response) throws Exception {
try{
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

String resourcePath="F:/netReaource/";
String fileName_old=request.getParameter("fileName");
String fileName=new String(fileName_old.getBytes("ISO-8859-1"),"UTF-8");//解决中午乱码
if(fileName!=null && !"".equals(fileName) ){
resourcePath+=fileName;
}
System.out.println("下载的文件名称=="+resourcePath);
File file=new File(resourcePath);
if(!file.exists()){
System.out.println("下载资源不存在");
return;
}
//设置响应类型及响应头
response.setContentType("application/x-msdownload");//有了这个响应才能在浏览器中弹出下载页面
response.addHeader("Content-Disposition", "attachment; filename=\""+ fileName_old + "\"");
FileInputStream fis=new FileInputStream(resourcePath);
OutputStream fos=response.getOutputStream();
int count=0;
byte[] buff=new byte[1024*1024];
while((count=fis.read(buff))!=-1){
fos.write(buff, 0,count);
}
fis.close();
fos.close();
}catch(Exception e){
e.printStackTrace();
}

}
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值