jsp+servlet上传文件,不用第三方jar包

//jsp
<form action="UploadFile" method="post">
<input type="file" name="file1" >
<input type="file" name="file2">
<input type="submit" value="上传">
</form>

//servlet
public class UploadFile extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

List<String> fileList = new ArrayList<String>();
String filename1 = request.getParameter("file1");
String filename2 = request.getParameter("file2");

if (filename1 != null && filename1.trim().length() > 0) {
filename1= new String(filename1.getBytes("iso-8859-1"), "UTF-8");
fileList.add(filename1);
}

if (filename2 != null && filename2.trim().length() > 0) {
filename2 = new String(filename2.getBytes("iso-8859-1"), "UTF-8");
fileList.add(filename2);
}

System.out.println("filename1="+filename1 +"\r\n"+ "filename2="+filename2);

//建立上传文件存放的路径
File uploadPath = new File(request.getRealPath("/downloadPath"));
//System.out.println("uploadPath="+uploadPath);
if (!uploadPath.exists()) {
uploadPath.mkdirs();
}

for (int i = 0; i < fileList.size(); i++) {
String fileName[] = new String[fileList.size()];
String exFileName[] = new String[fileList.size()];

//文件路径
String filePath = fileList.get(i);
//取上传的文件名称
fileName[i] = filePath.substring(filePath.lastIndexOf("\\")+1, filePath.length());
//取得文件的扩展名称
exFileName[i] = filePath.substring(filePath.lastIndexOf(".")+1, filePath.length());

//在存放的目录下新建文件
File uploadFileName = new File(uploadPath, fileName[i]);
System.out.println("uploadFileName="+uploadFileName);
if (!uploadFileName.exists()) {
uploadFileName.createNewFile();
}

FileInputStream inputStream = new FileInputStream(filePath);
//向服务器写入文件
FileOutputStream outputStream = new FileOutputStream(uploadPath+"/"+fileName[i]);

int c = inputStream.read();
System.out.println("-----------c:"+c);
byte[] bt = new byte[1024];
int num = inputStream.read(bt, 0, 512);
while (num != -1) {
outputStream.write(bt, 0, 1024);
num = inputStream.read(bt, 0, 1024);
}

inputStream.close();
outputStream.close();

}
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值