从类型Part中的Http Request获取图像文件,将其转换为Input-stream并将其保存到计算机但文件已损坏

时间:2016-08-01 23:33:48

标签: jsp servlets httpserver

我的Servlet代码在这里

protected void doPost(HttpServletRequest request,HttpServletResponse response)抛出ServletException,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();

}

此代码正常运行,保存的文件大小与上传文件相同,但是当我打开它时,它已损坏,

1 个答案:

答案 0 :(得分:0)

请尝试此代码。

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