import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 如果一个表单的类型是post且enctype为multipart/form-date
* 则所有数据都是以二进制的方式向服务器上传递。
* 所以req.getParameter("xxx")永远为null。
* 只可以通过req.getInputStream()来获取数据,获取正文的数据
*
* @author wangxi
*
*/
public class UpServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String txt = req.getParameter("txt");//返回的是null
System.err.println("txt is :"+txt);
System.err.println("=========================================");
InputStream in = req.getInputStream();
// byte[] b= new byte[1024];
// int len = 0;
// while((len=in.read(b))!=-1){
// String s = new String(b,0,len);
// System.err.print(s);
// }
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String firstLine = br.readLine();//读取第一行,且第一行是分隔符号,即随机字符串
String fileName = br.readLine();//第二行文件信息,从中截取出文件名
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);// xxxx.txt"
fileName = fileName.substring(0,fileName.length()-1);
br.readLine();
br.readLine();
String data = null;
//获取当前项目的运行路径
String projectPath = getServletContext().getRealPath("/up");
PrintWriter out = new PrintWriter(projectPath+"/"+fileName);
while((data=br.readLine())!=null){
if(data.equals(firstLine+"--")){
break;
}
out.println(data);
}
out.close();
}
}
/**
* DiskFileItemFactory构造的两个参数
* 第一个参数:sizeThreadHold - 设置缓存(内存)保存多少字节数据,默认为10K
* 如果一个文件没有大于10K,则直接使用内存直接保存成文件就可以了。
* 如果一个文件大于10K,就需要将文件先保存到临时目录中去。
* 第二个参数 File 是指临时目录位置
*
*/
public class Up2Servlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTf-8");
//获取项目的路径
String path = getServletContext().getRealPath("/up");
//第一步声明diskfileitemfactory工厂类,用于在指的磁盘上设置一个临时目录
DiskFileItemFactory disk =
new DiskFileItemFactory(1024*10,new File("/home/wang/"));
//第二步:声明ServletFileUpoload,接收上面的临时目录
ServletFileUpload up = new ServletFileUpload(disk);
//第三步:解析request
try {
List<FileItem> list = up.parseRequest(req);
//如果就一个文件
FileItem file = list.get(0);
//获取文件名,带路径
String fileName = file.getName();
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
//获取文件的类型
String fileType = file.getContentType();
//获取文件的字节码
InputStream in = file.getInputStream();
//声明输出字节流
OutputStream out = new FileOutputStream(path+"/"+fileName);
//文件copy
byte[] b = new byte[1024];
int len = 0;
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
out.close();
long size = file.getInputStream().available();
//删除上传的临时文件
file.delete();
//显示数据
resp.setContentType("text/html;charset=UTf-8");
PrintWriter op = resp.getWriter();
op.print("文件上传成功<br/>文件名:"+fileName);
op.print("<br/>文件类型:"+fileType);
op.print("<br/>文件大小(bytes)"+size);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<form action="<c:url value='/Up3Servlet'/>" method="post" enctype="multipart/form-data"> File1:<input type="file" name="txt"><br/> File2:<input type="file" name="txt"><br/> <input type="submit"/> </form>
public class Up3Servlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String path = getServletContext().getRealPath("/up");
//声明disk
DiskFileItemFactory disk = new DiskFileItemFactory();
disk.setSizeThreshold(1024*1024);
disk.setRepository(new File("d:/a"));
//声明解析requst的servlet
ServletFileUpload up = new ServletFileUpload(disk);
try{
//解析requst
List<FileItem> list = up.parseRequest(request);
//声明一个list<map>封装上传的文件的数据
List<Map<String,String>> ups = new ArrayList<Map<String,String>>();
for(FileItem file:list){
Map<String,String> mm = new HashMap<String, String>();
//获取文件名
String fileName = file.getName();
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
String fileType = file.getContentType();
InputStream in = file.getInputStream();
int size = in.available();
//使用工具类
FileUtils.copyInputStreamToFile(in,new File(path+"/"+fileName));
mm.put("fileName",fileName);
mm.put("fileType",fileType);
mm.put("size",""+size);
ups.add(mm);
file.delete();
}
request.setAttribute("ups",ups);
//转发
request.getRequestDispatcher("/jsps/show.jsp").forward(request, response);
}catch(Exception e){
e.printStackTrace();
}
}
}
public class UpDescServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");//可以获取中文的文件名
String path = getServletContext().getRealPath("/up");
DiskFileItemFactory disk =
new DiskFileItemFactory();
disk.setRepository(new File("d:/a"));
try{
ServletFileUpload up =
new ServletFileUpload(disk);
List<FileItem> list = up.parseRequest(request);
for(FileItem file:list){
//第一步:判断是否是普通的表单项
if(file.isFormField()){
String fileName = file.getFieldName();//<input type="text" name="desc">=desc
String value = file.getString("UTF-8");//默认以ISO方式读取数据
System.err.println(fileName+"="+value);
}else{//说明是一个文件
String fileName = file.getName();
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
file.write(new File(path+"/"+fileName));
System.err.println("文件名是:"+fileName);
System.err.println("文件大小是:"+file.getSize());
file.delete();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public class FastServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String path = getServletContext().getRealPath("/up");
DiskFileItemFactory disk =
new DiskFileItemFactory();
disk.setRepository(new File("d:/a"));
try{
ServletFileUpload up = new ServletFileUpload(disk);
//以下是迭代器模式
FileItemIterator it= up.getItemIterator(request);
while(it.hasNext()){
FileItemStream item = it.next();
String fileName = item.getName();
fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
InputStream in = item.openStream();
FileUtils.copyInputStreamToFile(in,new File(path+"/"+fileName));
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
//第一步:设置响应的类型
resp.setContentType("application/force-download");
//第二读取文件
String path = getServletContext().getRealPath("/up/"+name);
InputStream in = new FileInputStream(path);
//设置响应头
//对文件名进行url编码
name = URLEncoder.encode(name, "UTF-8");
resp.setHeader("Content-Disposition","attachment;filename="+name);
resp.setContentLength(in.available());
//第三步:开始文件copy
OutputStream out = resp.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
out.close();
in.close();
}
在使用J2EE流行框架时
<form action="fileUpload.action" method="post" enctype="multipart/form-data"> username: <input type="text" name="username"><br> file: <input type="file" name="file"><br> <input type="submit" value="submit"> </form>
public class FileUploadAction extends ActionSupport
{
private String username;
//注意,file并不是指前端jsp上传过来的文件本身,而是文件上传过来存放在临时文件夹下面的文件
private File file;
//提交过来的file的名字
//struts会自动截取上次文件的名字注入给该属性
private String fileFileName;
//getter和setter此时为了节约篇幅省掉
@Override
public String execute() throws Exception
{
//保存上传文件的路径
String root = ServletActionContext.getServletContext().getRealPath("/upload");
//获取临时文件输入流
InputStream is = new FileInputStream(file);
//输出文件
OutputStream os = new FileOutputStream(new File(root, fileFileName));
//打印出上传的文件的文件名
System.out.println("fileFileName: " + fileFileName);
// 因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的fileFileName是否相同
System.out.println("file: " + file.getName());
System.out.println("file: " + file.getPath());
byte[] buffer = new byte[1024];
int length = 0;
while(-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer);
}
os.close();
is.close();
return SUCCESS;
}
}
public class FileDownloadAction extends ActionSupport
{
//要下载文件在服务器上的路径
private String path;
//要下载文件的文件名
private String downloadFileName;
//写入getter和setter
public InputStream getDownloadFile()
{
return ServletActionContext.getServletContext().getResourceAsStream(path);
}
@Override
public String execute() throws Exception
{
//当前action默认在valuestack的栈顶
setDownloadFileName(xxx);
return SUCCESS;
}
}
<action name="fileDownload" class="com.struts2.FileDownloadAction">
<result name="download" type="stream">
<param name="contentDisposition">attachment;fileName="${downloadFileName}"</param>
<param name="inputName">downloadFile</param>
</result>
</action>
@Controller
@RequestMapping(value="fileOperate")
public class FileOperateAction {
@RequestMapping(value="upload")
public String upload(HttpServletRequest request,@RequestParam("file") MultipartFile photoFile){
//上传文件保存的路径
String dir = request.getSession().getServletContext().getRealPath("/")+"upload";
//原始的文件名
String fileName = photoFile.getOriginalFilename(); //获取文件扩展名
String extName = fileName.substring(fileName.lastIndexOf("."));
//防止文件名冲突,把名字小小修改一下
fileName = fileName.substring(0,fileName.lastIndexOf(".")) + System.nanoTime() + extName;
FileUtils.writeByteArrayToFile(new File(dir,fileName),photoFile.getBytes());
return "success";
}
}
@RequestMapping("/download")
public String download(String fileName, HttpServletRequest request,
HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
try {
InputStream inputStream = new FileInputStream(new File(文件的路径);
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 返回值要注意,要不然就出现下面这句错误!
//java+getOutputStream() has already been called for this response
return null;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有