图片上传下载工具类
package com.gdh.unit;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class FileUploadUtil {
public static String uploadPhoto(MultipartFile loadimg) {
String path = "D:/upload";
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
String filename = loadimg.getOriginalFilename();
System.out.println(filename);
String filepath = path + "/" + filename;
File file = new File(filepath);
System.out.println(file + "这是图片保存的路径");
try {
loadimg.transferTo(file);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return filepath;
}
public static void showPhoto(String photo, HttpServletResponse response) throws IOException {
FileInputStream fis = null;
ServletOutputStream os = null;
try {
fis = new FileInputStream(photo);
os = response.getOutputStream();
byte[] b = new byte[1024];
while (fis.read(b) != -1) {
os.write(b);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void downLoad(String filepath, HttpServletRequest request, HttpServletResponse response) {
response.setContentType(request.getSession().getServletContext().getMimeType(filepath));
response.setHeader("Content-Disposition", "attachment;filename=" + filepath);
try {
InputStream in = new FileInputStream(filepath);
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
while (in.read(b) != -1) {
out.write(b);
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}