将上传的文件保存在特定的位置 [英] Saving uploaded file in specific location

查看:189
本文介绍了将上传的文件保存在特定的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下处理文件在服务器上的代码。但如何将文件保存到服务器上的特定位置?

pre $ import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import org.apache.commons.fileupload.FileItem;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;



$ b / **
*这是一个如何使用UploadAction类的例子。
*
*此servlet将所有收到的文件保存在临时文件夹
*中,并在用户发送删除请求时将其删除。
*
* @author Manolo CarrascoMoñino
*
* /
public class SampleUploadServlet extends UploadAction {

private static final long serialVersionUID = 1L;

Hashtable< String,String> receivedContentTypes = new Hashtable< String,String>();
/ **
*维护一份收到文件及其内容类型的列表。
* /
Hashtable< String,File> receivedFiles = new Hashtable< String,File>();
$ b $ / **
*重写exe​​cuteAction以将接收到的文件保存在自定义位置
*中,并从会话中删除这些项目。
* /
@Override
public String executeAction(HttpServletRequest request,List< FileItem> sessionFiles)throws UploadActionException {
String response =;
int cont = 0;
for(FileItem item:sessionFiles){
if(false == item.isFormField()){
cont ++;
try {
///根据客户端中的远程文件名创建一个新文件
// String saveName = item.getName()。replaceAll([\\\\ \\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\' / File file = new File(/ tmp /+ saveName);

///创建临时文件放在/ tmp中(只能在unix下运行)
// File file = File.createTempFile(upload-,.bin,new File(/ tmp));

///创建临时文件放置在默认的系统临时文件夹
File file = File.createTempFile(upload-,.bin);
item.write(file);

///用接收的文件保存列表
receivedFiles.put(item.getFieldName(),file);
receivedContentTypes.put(item.getFieldName(),item.getContentType());

///编写一个xml消息与完整的文件信息
resp onse + =< file-+ cont +-field>+ item.getFieldName()+< / file-+ cont +-field> \\\
;
response + =< file-+ cont +-name> + item.getName()+< / file-+ cont +-name> \\\
;
response + =< file-+ cont +-size> + item.getSize()+< / file-+ cont +-size> \\\
;
response + =< file-+ cont +-type> + item.getContentType()+< / file-+ cont +type> \\\
;

catch(Exception e)
{
}
}
}

///从会话中删除文件,因为我们有一个副本
removeSessionFileItems(request);

///将收到的文件信息发送给客户端。
return< response> \\\
+ response +< / response> \\\
;
}

/ **
*获取上传文件的内容。
* /
@Override
public void getUploadedFile(HttpServletRequest request,HttpServletResponse response)throws IOException {
String fieldName = request.getParameter(PARAM_SHOW);
文件f = receivedFiles.get(fieldName);
if(f!= null){
response.setContentType(receivedContentTypes.get(fieldName));
FileInputStream is = new FileInputStream(f);
copyFromInputStreamToOutputStream(is,response.getOutputStream());
} else {
renderXmlResponse(request,response,ERROR_ITEM_NOT_FOUND);
}
}

/ **
*当用户发送删除请求时删除一个文件。
* /
@Override
public void removeItem(HttpServletRequest request,String fieldName)throws UploadActionException {
File file = receivedFiles.get(fieldName);
receivedFiles.remove(fieldName);
receivedContentTypes.remove(fieldName);
if(file!= null){
file.delete();



$ b $ / code $ / pre

解决方案

您应该使用 File#createTempFile()取代目录

 档案档案= File.createTempFile(upload-,.bin,新档案(/ path / to /你/上传)); 
item.write(file);

或者如果您真的想将临时文件移动到其他位置之后 ,请使用 File#renameTo()

 文件destination = new File(/ path / to / your / uploads,file.getName()); 
file.renameTo(destination);


I have the following code which handles files upload on the server. But how to save the file to a specific location on the server

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import org.apache.commons.fileupload.FileItem;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




/**
 * This is an example of how to use UploadAction class.
 *  
 * This servlet saves all received files in a temporary folder, 
 * and deletes them when the user sends a remove request.
 * 
 * @author Manolo Carrasco Moñino
 *
 */
public class SampleUploadServlet extends UploadAction {

  private static final long serialVersionUID = 1L;

  Hashtable<String, String> receivedContentTypes = new Hashtable<String, String>();
  /**
   * Maintain a list with received files and their content types. 
   */
  Hashtable<String, File> receivedFiles = new Hashtable<String, File>();

  /**
   * Override executeAction to save the received files in a custom place
   * and delete this items from session.  
   */
  @Override
  public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
    String response = "";
    int cont = 0;
    for (FileItem item : sessionFiles) {
      if (false == item.isFormField()) {
        cont++;
        try {
          /// Create a new file based on the remote file name in the client
          // String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_");
          // File file =new File("/tmp/" + saveName);

          /// Create a temporary file placed in /tmp (only works in unix)
          // File file = File.createTempFile("upload-", ".bin", new File("/tmp"));

          /// Create a temporary file placed in the default system temp folder
          File file = File.createTempFile("upload-", ".bin");
          item.write(file);

          /// Save a list with the received files
          receivedFiles.put(item.getFieldName(), file);
          receivedContentTypes.put(item.getFieldName(), item.getContentType());

          /// Compose a xml message with the full file information
          response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n";
          response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n";
          response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n";
          response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "type>\n";
        } 
        catch (Exception e) 
        {
        }
      }
    }

    /// Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    /// Send information of the received files to the client.
    return "<response>\n" + response + "</response>\n";
  }

  /**
   * Get the content of an uploaded file.
   */
  @Override
  public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String fieldName = request.getParameter(PARAM_SHOW);
    File f = receivedFiles.get(fieldName);
    if (f != null) {
      response.setContentType(receivedContentTypes.get(fieldName));
      FileInputStream is = new FileInputStream(f);
      copyFromInputStreamToOutputStream(is, response.getOutputStream());
    } else {
      renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND);
   }
  }

  /**
   * Remove a file when the user sends a delete request.
   */
  @Override
  public void removeItem(HttpServletRequest request, String fieldName)  throws UploadActionException {
    File file = receivedFiles.get(fieldName);
    receivedFiles.remove(fieldName);
    receivedContentTypes.remove(fieldName);
    if (file != null) {
      file.delete();
    }
  }

}

解决方案

You should use File#createTempFile() which takes a directory instead.

File file = File.createTempFile("upload-", ".bin", new File("/path/to/your/uploads"));
item.write(file);

Or if you actually want to move the temp file to another location afterwards, use File#renameTo().

File destination = new File("/path/to/your/uploads", file.getName());
file.renameTo(destination);

这篇关于将上传的文件保存在特定的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆