您的位置:首页 > 编程语言 > Java开发

解决Struts2上传docx文件变大的问题

2016-01-22 01:02 513 查看
今有一项目采用struct2开发,用到了其中的上传文件功能,发现doc文件和图片文件上传都是正常的唯有office的docx版本文件上传发生错误。上传以后的docx能用office2007打开但是却提出文件格式错误的信息,经过与源文件进行对比发现上传后的文件多个10K而导致文件格式错误。经过检查发现是拷贝文件的时候发生错误

原先的拷贝文件的程序代码如下:

public void copy(File src, File dst) {

try {

InputStream in = null;

OutputStream out = null;

try {

in = new BufferedInputStream(new FileInputStream(src),

BUFFER_SIZE);

out = new BufferedOutputStream(new FileOutputStream(dst),

BUFFER_SIZE);

byte[] buffer = new byte[BUFFER_SIZE];

while (in.read(buffer) != -1) {

out.write(buffer);

}

} finally {

if (null != in) {

in.close();

}

if (null != out) {

out.close();

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

现在改进为如下:

private static void copy(File src, File dst) {

try {

InputStream in = null;

OutputStream out = null;

try {

in = new BufferedInputStream(new FileInputStream(src),

BUFFER_SIZE);

out = new BufferedOutputStream(new FileOutputStream(dst),

BUFFER_SIZE);

byte[] buffer = new byte[BUFFER_SIZE];

int i = 0;

while ((i = in.read(buffer)) > 0) {

out.write(buffer, 0, i);

}

} finally {

if (null != out) {

out.close();

}

if (null != in) {

in.close();

}

}

} catch (Exception e) {

e.printStackTrace();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: