当前位置:编程学习 > JAVA >>

Java Web上传文件时遇到的问题

用Struts2上传文件时,出现了如图所示的警告,有两种情况,第一种是上传的文件最后得到的是临时文件,第二种情况是最后得到的是我想要上传的文件,但是服务器端还是会出现如图所示的警告,请大牛指点迷津!谢谢 Java web Struts2 文件上传 --------------------编程问答-------------------- 存放上传文件的文件夹是只读的吧 --------------------编程问答-------------------- 同意楼上观点
如果是WINDOWS做服务器的话,检查下文件夹权限 --------------------编程问答-------------------- import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.upload.FormFile;

public class FileUtil {
/**
 * 上传文件
 * 
 * @param file 
 * @param filePath
 * 
 * @throws Exception
 */
public static void runUploadFile(FormFile file, String filePath) throws Exception 
{
InputStream  streamIn  = null;
OutputStream streamOut = null;
if (file != null) 
{
try 
{
streamOut = new FileOutputStream(filePath);
streamIn = file.getInputStream();

int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) { streamOut.write(buffer, 0, bytesRead);}

}catch(IOException e)
        {
e.fillInStackTrace();
        }finally
        {
            try 
            {
if(streamIn != null)
streamIn.close();
if(streamOut != null)
streamOut.close();
            } 
            catch (IOException e) 
            {
            }             
        }
}
}
/**
 * 下载文件
 * 
 * @param filePath 
 * @param response
 * 
 * @throws Exception
 */
public static void runDownFile(String filePath, HttpServletResponse response) throws Exception 
{
try 
{
File file = new File(filePath);
String fileName = new String(filePath.substring(filePath.lastIndexOf("\\")+1, filePath.length()).getBytes("gbk"),"ISO-8859-1");  //windows
response.setContentType("application");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
FileInputStream fis=new FileInputStream(file);
BufferedInputStream buff=new BufferedInputStream(fis);
        byte [] b=new byte[1024];//相当于我们的缓存
        long k=0;//该值用于计算当前实际下载了多少字节
        //从response对象中得到输出流,准备下载
        OutputStream myout=response.getOutputStream();
        //开始循环下载
        while(k<file.length()){
            int j=buff.read(b,0,1024);
            k+=j;
            //将b中的数据写到客户端的内存
            myout.write(b,0,j);
        }
        //将写入到客户端的内存的数据,刷新到磁盘
        buff.close();
fis.close();
myout.close();
        myout.flush();


catch (FileNotFoundException se)
{

}
catch(IOException e)
        {
e.printStackTrace();
        }
}
}
--------------------编程问答-------------------- 同意一楼的说法,检查权限 --------------------编程问答-------------------- windows上的文件夹好像都是只读的吧
补充:Java ,  Web 开发
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,