文件上传和下载

2020/8/17

   今天在公司学习文件上传和下载,任然是前后端分离

文件上传和下载

package org.lanqiao.servlet;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
* Servlet implementation class UpLoad
*/
@WebServlet("/UpLoad")
public class UpLoad extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");

System.out.println(request.getParameter("name"));

Collection<Part> parts = request.getParts();
int i=1;
// "image/jpeg".equals null=字符串会报错 反过来
for(Part part:parts) {
System.out.println(part.getContentType());
if ("image/jpeg".equals(part.getContentType())) {
//获取上传文件对象 currentTimeMillis()时间戳 i++ getSession().getId()(防止照片重复) path路径
String path=request.getServletContext().getRealPath("/img");
String name=System.currentTimeMillis()+"-"+i+++request.getSession().getId();
//开始保存图片
System.out.println(path+"/"+name+"jpg");
part.write(path+"/"+name+"jpg");
}
}
}
}

文件上传和下载

package org.lanqiao.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 

/**
* Servlet implementation class DoLoad
*/
@WebServlet("/DoLoad")
public class DoLoad extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String name=request.getParameter("name");

response.setContentType("application/x-download");
//设置下载数据的格式
response.addHeader("Content-Disposition","attachment;filename="+name+".jpg");

//获取需要下载的文件如今
File file=new File(request.getServletContext().getRealPath("/img/"+name+".jpg"));
System.out.println("-------------学习IO以后讲解------------------------");
//创建文件流
FileInputStream fis=new FileInputStream(file);
//每次读写1024KB
byte[] b=new byte[1024];
int i=-1;
while ((i=fis.read(b))>0) {
//开始给客户端传输数据
response.getOutputStream().write(b,0,i);

}
}
}

文件上传和下载

上一篇:kubernetes集群:添加worker 报错“[kubelet-check] Initial timeout of 40s passed. error execution phase kubelet-start: error uploading crisocket: timed out waiting for the condition”


下一篇:ios 利用RunLoop的原理去监控卡顿