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();
}
}
}
}