gpt4 book ai didi

java - 为什么我的图像出现乱码?

转载 作者:搜寻专家 更新时间:2023-11-01 02:35:07 24 4
gpt4 key购买 nike

我有一些 Java 代码使用 servlet 和 Apache Commons FileUpload 将文件上传到设定的目录。它对字符数据(例如文本文件)工作正常,但图像文件出现乱码。我可以打开它们,但图像看起来不正常。这是我的代码:

小服务程序

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String customerPath = "\\leetest\\";

// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (isMultipart) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();

// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
if (item.isFormField()) {
// Form field. Ignore for now
} else {
BufferedInputStream stream = new BufferedInputStream(item
.openStream());
if (stream == null) {
LOGGER
.error("Something went wrong with fetching the stream for field "
+ name);
}

byte[] bytes = StreamUtils.getBytes(stream);
FileManager.createFile(customerPath, item.getName(), bytes);

stream.close();
}
}
}
} catch (Exception e) {
throw new UploadException("An error occured during upload: "
+ e.getMessage());
}
}

StreamUtils.getBytes(stream) 看起来像:

public static byte[] getBytes(InputStream src, int buffsize)
throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buff = new byte[buffsize];
while (true) {
int nBytesRead = src.read(buff);
if (nBytesRead < 0) {
break;
}
byteStream.write(buff);
}

byte[] result = byteStream.toByteArray();
byteStream.close();

return result;
}

最后 FileManager.createFile 看起来像:

public static void createFile(String customerPath, String filename,
byte[] fileData) throws IOException {
customerPath = getFullPath(customerPath + filename);
File newFile = new File(customerPath);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}

FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(fileData);
outputStream.close();
}

谁能发现我做错了什么?

干杯,李

最佳答案

我不喜欢的是 StreamUtils.getBytes() 的这个 block :

 1 while (true) {
2 int nBytesRead = src.read(buff);
3 if (nBytesRead < 0) {
4 break;
5 }
6 byteStream.write(buff);
7 }

在第 6 行,它写入整个缓冲区,无论读入多少字节。我不相信情况总是如此。像这样更正确:

 1 while (true) {
2 int nBytesRead = src.read(buff);
3 if (nBytesRead < 0) {
4 break;
5 } else {
6 byteStream.write(buff, 0, nBytesRead);
7 }
8 }

请注意第 5 行的“else”,以及第 6 行的两个附加参数(数组索引起始位置和要复制的长度)。

我可以想象对于较大的文件,如图像,缓冲区在填充之前返回(也许它正在等待更多)。这意味着您会无意中写入保留在缓冲区尾部的旧数据。这几乎肯定会在 EoF 的大部分时间发生,假设缓冲区 > 1 字节,但 EoF 的额外数据可能不是导致损坏的原因......它只是不可取的。

关于java - 为什么我的图像出现乱码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com