Serlvet+jsp实现图片上传

Sevelt 代码如下

  package com.ray;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

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

 

public class Upload extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String fraternityLogo =  new String(request.getParameter("fLogo").getBytes("ISO-8859-1"),"utf-8");
  String fraternityName = new String(request.getParameter("fName").getBytes("ISO-8859-1"),"utf-8");
  String tempPath = "";// 图片在系统中的路径
  String url = "";
  if (!fraternityLogo.equals("")) {
   File file = new File(fraternityLogo);

   // 取得文件名及后缀!!
   String tupName = file.getName();

   String fileName = tupName.substring(0, tupName.indexOf("."));
   String fileEnd = tupName.substring(tupName.indexOf(".") + 1,
     tupName.length());

   if (fileEnd.equals("jpg") || fileEnd.equals("JPG")
     || fileEnd.equals("gif") || fileEnd.equals("GIF")) {
    // web 图片路径文件夹路径
    String webpath = getServletContext().getRealPath("/") + "img\\"
      + fraternityName + "." + fileEnd;
    
    tempPath = fraternityName + "." + fileEnd;

    FileInputStream inStream = new FileInputStream(file);
    byte[] b = new byte[(int) file.length()];
    FileOutputStream fos = new FileOutputStream(webpath);
    int n;
    while ((n = inStream.read(b)) != -1) {
     fos.write(b, 0, n);
    }
    fos.flush();// 写到磁盘上
    fos.close();// 关闭文件流
    }
   }
 }

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

}

 

jsp代码

 

<body>
    <h3 align="center">servlet+jap 实现图片上传</h3>
    <form action="upload.do" method="post">
     文件名称:<input type="text" name="fName"><br>
     <input type="file" name="fLogo"/>
     <input type="submit" value="上传"/>
    </form>
  </body>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值