1

私はこの問題を抱えています。私はSpringを使用し、添付ファイル(doc、pdf、png ...)をサーバーファイルシステムに保存します。次に、ファイルのパスと名前をデータベースに保存します。このファイルをブラウザへのリンクとして読み取るにはどうすればよいですか?

ファイルをWebの位置に書き込み、この場所をブラウザーに渡すことを考えました。それは良い習慣ですか?しかし、視覚化後にファイルを削除するにはどうすればよいですか?

質問が明確であることを願っています。

ここに画像の説明を入力してください

書くために私は使用します:

 /** what write for reach temp-file folder (my project name is intranet)
   I thougth TEMP_FOLDER=""/intranet/resources/temp-files/";
   but It doesnt work. ioexception (The system cannot find the path specified)
 */
 final static String TEMP_FOLDER=?????

public static String createTempFile(String originalPathFile,String fileName){
String tempPathFile="";
try {
    InputStream inputStream = new FileInputStream(originalPathFile);
    tempPathFile=TEMP_FOLDER+fileName;
    File tempFile = new File(tempPathFile);

    OutputStream out = new FileOutputStream(tempFile);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = inputStream.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }
    out.flush();
    out.close();
} catch (IOException ioe) {
     System.out.println("Error while Creating File in Java" + ioe);
}

return tempPathFile;
  }
4

2 に答える 2

2

このファイルをブラウザへのリンクとして読み取るにはどうすればよいですか?

次のリンクをJSPに配置します

<a href="<c:url value="/fileDownloadController/downloadFile?filename=xyz.txt"/>" title="Download xyz.txt"></a>

コントローラ内:

@Controller
@RequestMapping("/fileDownloadController")
public class FileDownloadController
{
    @RequestMapping("/downloadFile")
    public void downloadFile( 
        @RequestParam String filename,
        HttpServletResponse response)
    {
        OutputStream outputStream = null;
        InputStream in = null;
        try {
            in = new FileInputStream("/tmp/" + filename); // I assume files are at /tmp
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            response.setHeader(
                "Content-Disposition",
                "attachment;filename=\"" + filename + "\"");
            outputStream = response.getOutputStream();
            while( 0 < ( bytesRead = in.read( buffer ) ) )
            {
                outputStream.write( buffer, 0, bytesRead );
            }
        }
        finally
        {
            if ( null != in )
            {
                in.close();
            }
        }

    }
}
于 2012-11-29T01:12:14.837 に答える
1

IOUtilsを使用してこの質問に入力する人々に役立つ可能性のある別の回答:

IOUtils.copy(new FileInputStream("filename"), outputStream);
于 2014-01-07T17:51:35.233 に答える