用java代码写一个图片上传下载的功能
时间: 2023-11-28 12:04:10 浏览: 30
以下是一个简单的 Java 代码实现图片上传下载功能:
1. 图片上传
```
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class ImageUploadUtil {
public static void upload(MultipartFile file, String filePath) throws IOException {
File dest = new File(filePath);
FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
}
}
```
使用时,只需要调用 `upload` 方法即可,其中 `file` 是上传的图片文件,`filePath` 是保存到服务器的路径。
2. 图片下载
```
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
public class ImageDownloadUtil {
public static void download(String filePath, HttpServletResponse response) throws Exception {
File file = new File(filePath);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
response.addHeader("Content-Length", "" + file.length());
response.setContentType("application/octet-stream");
FileInputStream fis = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = bis.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
bos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
if (fis != null) {
fis.close();
}
}
}
}
```
使用时,只需要调用 `download` 方法即可,其中 `filePath` 是下载图片的路径,`response` 是 HttpServletResponse 对象。