ssm上传图片



controller写法

public String addStore(OOmallStore ooStore,@RequestParam("storepic") MultipartFile filedata,HttpServletRequest request) throws IOException{
String url=  request.getSession().getServletContext().getRealPath(“\image”);
  if (filedata != null && !filedata.isEmpty()) { // 判断是否上传文件

        UploadPic.upload(filedata,url);
        ooStore.setStoreImage(newFileName);
  }

  oomallStoreService.insert(ooStore);
  
  return  "/ooyanjing/m_get_supplier.action" ;
 }





package com.ooyanjing.util.method;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.annotation.processing.FilerException;
import org.springframework.web.multipart.MultipartFile;
public class UploadPic {
 public static String newFileName;
 public static void upload(MultipartFile filedate, String url){
  
  if (filedate != null && !filedate.isEmpty()) { // 判断是否上传文件
     
     String fileName = filedate.getOriginalFilename();// 获取文件名
     String extensionName = fileName
       .substring(fileName.lastIndexOf(".") + 1);// 获取图片扩展名
     newFileName = String.valueOf(System.currentTimeMillis())
       + "." + extensionName;
     try {
      InputStream is = filedate.getInputStream();
      FileOutputStream fos = new FileOutputStream(new File(url,newFileName));
      byte[] buffer = new byte[8192]; // 每次读8K字节
      int count = 0;
      // 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中
      while ((count = is.read(buffer)) > 0) {
       fos.write(buffer, 0, count); // 向服务端文件写入字节流
      }
      fos.close(); // 关闭FileOutputStream对象
      is.close(); // InputStream对象
     } catch (FileNotFoundException e) {
  
      e.printStackTrace();
     } catch (IOException e) {
      e.printStackTrace();
  
     }
   }
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值