从类型为Part的Http请求中获取一个图像文件,将其转换为输入流并保存到计算机,但文件已损坏



我的Servlet代码在这里

protected void doPost(HttpServlet请求,HttpServlet响应)抛出Servlet异常,IOException{

    Part image = request.getPart("pic");
    InputStream is =image.getInputStream();
    byte[] targetArray= new byte[is.available()];

    FileOutputStream fos = new FileOutputStream("F:\image\abc.jpg");
    fos.write(targetArray);
    is.close();
    fos.close();

}

这个代码正在工作,保存的文件大小与上传的文件相同,但当我打开它时,它已损坏,

请尝试此代码。

//add to your imports
import java.nio.file.*;
Part image = request.getPart("pic");
Path path = FileSystems.getDefault().getPath("F:/image", "abc.jpg");
try(InputStream is =image.getInputStream()){
    Files.copy(is, path);
}

最新更新